从 C 中的 MMAP 中删除空格
我正在尝试删除文件中包含的空格,在使用 mmap 读取文件后,我继续使用 for 循环删除空格并将下一个指针移至当前索引,但它似乎不起作用。这是我的代码来说明:
static unsigned long get_size_by_fd(int fd) {
struct stat statbuf;
if(fstat(fd, &statbuf) < 0) exit(-1);
return statbuf.st_size;
}
fd = open("/home/text.txt", O_RDONLY);
file_size = get_size_by_fd(fd);
fb = mmap(0, file_size, PROT_READ || PROT_WRITE, MAP_SHARED, fd, 0);
for (i = 0; i<file_size; i++) {
if (fb[i] == 0x20) {
fb[i] = fb[i++];
}
}
I'm trying to remove white spaces contained in a file and after I've read it using mmap, I proceed by removing white spaces by using a for-loop and shirting the next pointer to the current index but it doesnt seem to work. Here's my code to illustrate:
static unsigned long get_size_by_fd(int fd) {
struct stat statbuf;
if(fstat(fd, &statbuf) < 0) exit(-1);
return statbuf.st_size;
}
fd = open("/home/text.txt", O_RDONLY);
file_size = get_size_by_fd(fd);
fb = mmap(0, file_size, PROT_READ || PROT_WRITE, MAP_SHARED, fd, 0);
for (i = 0; i<file_size; i++) {
if (fb[i] == 0x20) {
fb[i] = fb[i++];
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
赋值
fb[i] = fb[i++];
中没有序列点,因此您会得到未指定的结果。最好写得直白一些:我还添加了一个额外的边界检查(考虑末尾是否有空格)。
请注意,您的程序对文件编码进行了假设。
There is no sequence point in the assignment
fb[i] = fb[i++];
so you get unspecified results. Better to write it plainly:I also added an additional bounds check (consider when there are spaces at the end).
Note that your program makes assumptions on the file encoding.
如果要删除所有空格,则必须使用两个索引:
循环终止后,
j
告诉您必须以某种方式强制执行的新大小(可能使用truncate() 在文件上)。
If you want to remove all spaces, you must use two indexes:
After the loop has terminated,
j
tells you the new size which you must somehow enforce (probably withtruncate()
on the file).您还应该打开文件描述符进行读写!
You should also open the file descriptor for reading and writing!