C Delete last n characters from file

不打扰是莪最后的温柔 提交于 2019-12-05 06:14:37

Why not use:

   #include <unistd.h>
   #include <sys/types.h>

   int truncate(const char *path, off_t length);
   int ftruncate(int fd, off_t length);

like for instance:

    charsToDelete = 5;
    fseeko(InputFile,-charsToDelete,SEEK_END);
    position = ftello(InputFile);
    ftruncate(fileno(InputFile), position);

Read all but n bytes from the file and write to a temporary file, close the original file, rename temporary file as original file.

Or use e.g. truncate or similar function if you have it.


Also, failure to open the file doesn't have to be that it can't be found, You should check errno on failure to see what the error is. Use e.g. strerror to get a printable string from the error code.

Unfortunately, mmap does not allow you to change size of underlying file object.

Instead, I would recommend to simply truncate your file, use something like this:

truncate(filename, new_length);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!