从 C 中的 MMAP 中删除空格

发布于 2024-12-19 21:02:58 字数 498 浏览 4 评论 0原文

我正在尝试删除文件中包含的空格,在使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

空袭的梦i 2024-12-26 21:02:58

赋值 fb[i] = fb[i++]; 中没有序列点,因此您会得到未指定的结果。最好写得直白一些:

if (fb[i] == 0x20 && i + 1 < file_size))
{
    fb[i] = fb[i + 1];
    ++i;
}

我还添加了一个额外的边界检查(考虑末尾是否有空格)。

请注意,您的程序对文件编码进行了假设。

There is no sequence point in the assignment fb[i] = fb[i++]; so you get unspecified results. Better to write it plainly:

if (fb[i] == 0x20 && i + 1 < file_size))
{
    fb[i] = fb[i + 1];
    ++i;
}

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.

丢了幸福的猪 2024-12-26 21:02:58

如果要删除所有空格,则必须使用两个索引:

for (i = 0, j = 0; i<file_size; i++) {
    if (fb[i] != 0x20) {
        fb[j++] = fb[i];
    }
}

循环终止后,j 告诉您必须以某种方式强制执行的新大小(可能使用truncate() 在文件上)。

If you want to remove all spaces, you must use two indexes:

for (i = 0, j = 0; i<file_size; i++) {
    if (fb[i] != 0x20) {
        fb[j++] = fb[i];
    }
}

After the loop has terminated, j tells you the new size which you must somehow enforce (probably with truncate() on the file).

著墨染雨君画夕 2024-12-26 21:02:58

您还应该打开文件描述符进行读写!

You should also open the file descriptor for reading and writing!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文