这个问题在这里已经有了答案:
How to truncate a file in C?
(6 个回答)
3年前关闭。
我想删除文本文件的最后一个字符。我有一个保存字符串的代码,我只需要删除最后一个 '\n'。
我已经尝试做:
fseek(fp, -1, SEEK_END);
fputs("", fp);
这是完整的代码:
void saveGIF(FrameNode** head)
{
FILE* fp = 0;
FrameNode* curr = *head;
int i = 1;
int howManyFrames = framesInList(head);
char c = 0;
char filePath[SIZE] = { 0 };
if (curr == NULL)
{
printf("Nothing to save, add more frames and than save\n");
}
else
{
printf("Where to save the project? enter a full path and file name\n");
getchar();
myFgets(filePath, SIZE);
fp = fopen(filePath, "w+");
if (fp != NULL)
{
while (curr)
{
fprintf(fp, "%s %d %s\n", curr->frame->name, curr->frame->duration, curr->frame->path);
curr = curr->next;
i++;
}
fseek(fp, -1, SEEK_END);
fputs("", fp);
fclose(fp);
}
else
{
printf("Error! canot create file\n");
}
}
}
最佳答案
在 ISO C 中,唯一的方法是在一个临时名称下写出整个文件的新副本,然后使用 rename
将其名称更改为旧名称。没有办法就地缩短文件。 (如果您使用的是 Windows,您可能必须使用 remove
之前的旧名称 rename
才有效。)
POSIX 添加了 ftruncate
可用于使文件更短(或更长)的操作。大多数常见的操作系统都支持 POSIX 功能,但 Windows 不支持。根据您在 Windows 上使用的编译器,您可能仍然有一个名为 ftruncate
的函数。 ,不过,因为 Windows 上的 C 运行时经常试图伪造 POSIX 功能的一个子集——其中许多伪造是不可靠的,但我承认我不知道人们怎么会搞砸 ftruncate
鉴于 Windows 本身确实具有等效的原始操作,它只是具有不同的名称( SetEndOfFile
)。
关于c - 如何删除c中文本文件中的最后一个字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50975968/