C从文件中删除最后n个字符 [英] C Delete last n characters from file
问题描述
我需要使用C代码从文件中删除最后n个字符.一开始,我试图使用'\ b',但它返回了Segmentation Fault.我在此处和
I need to delete the last n characters from a file using C code. At fist I was trying to use '\b', but it returns a Segmentation Fault. I have seen interesting answers to similar questions here and here, but I would prefer to use mmap
function to do this, if it's possible. I know it could be simpler to truncate the file by creating a temp file, and writing chars to temp until some offset of the original file. The problem is I don't seem to understand how to use mmap
function to do this, can't see what parameters I need to pass to that function, specially address
, length
and offset
. From what I've read, I should use MAP_SHARED
in flags
and PROT_READ|PROT_WRITE
in protect
.
函数定义为:
void * mmap (void *address, size_t length, int protect, int flags, int filedes, off_t offset)
这是我的主要爱好:
int main(int argc, char * argv[])
{
FILE * InputFile;
off_t position;
int charsToDelete;
if ((InputFile = fopen(argv[1],"r+")) == NULL)
{
printf("tdes: file not found: %s\n",argv[1]);
}
else
{
charsToDelete = 5;
fseeko(InputFile,-charsToDelete,SEEK_END);
position = ftello(InputFile);
printf("Pos: %d\n",(int)position);
int i;
//for(i = 0;i < charsToDelete;i++)
//{
// putc(InputFile,'\b');
//}
}
fclose(InputFile);
return 0;
}
推荐答案
为什么不使用:
#include <unistd.h>
#include <sys/types.h>
int truncate(const char *path, off_t length);
int ftruncate(int fd, off_t length);
例如:
charsToDelete = 5;
fseeko(InputFile,-charsToDelete,SEEK_END);
position = ftello(InputFile);
ftruncate(fileno(InputFile), position);
这篇关于C从文件中删除最后n个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!