我希望删除文本文件的最后一个字符。我有一个保存字符串的代码,我只需要删除最后一个'\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");
}
}
}
fputs
。 - Mad Physicistftruncate()
或truncate()
。在Windows上,答案可能会有所不同。 - Jonathan Lefflerfputs(" ", fp)
将最后的换行符覆盖为一个空格,但写入空字符串不会改变文件内容。你也可以使用fwrite()
写入一个空字节来覆盖换行符。然而,这两种方法都不会缩短文件长度,不像truncate()
及其相关函数。 - Jonathan Leffler