我需要使用 C 代码从文件中删除最后 n 个字符。起初我尝试使用“\b”,但它返回了分段错误。我看到类似问题的有趣答案here https://stackoverflow.com/questions/584639/truncate-file and here https://stackoverflow.com/questions/1311683/is-there-any-basic-way-to-delete-something-from-opened-file,但我更愿意使用mmap
如果可能的话,可以使用函数来执行此操作。我知道通过创建临时文件并将字符写入临时文件直到原始文件的某个偏移量来截断文件可能会更简单。问题是我似乎不明白如何使用mmap
函数来执行此操作,看不到我需要传递给该函数的参数,特别是address
, length
and offset
。根据我读过的内容,我应该使用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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)