如何删除C中文本文件中的最后一个字符?

时间:2018-06-21 19:10:09

标签: c

我想删除文本文件的最后一个字符。我有一个保存字符串的代码,我只需要删除最后一个'\ 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");
        }
    }
}

1 个答案:

答案 0 :(得分:2)

在ISO C中,唯一的方法是以临时名称写出整个文件的新副本,然后使用rename将其名称更改为旧名称。没有办法缩短文件的位置。 (如果您使用的是Windows,则可能必须remove之前使用rename才能使用旧名称。)

POSIX添加了ftruncate操作,该操作可用于使文件变短(或变长)。大多数常见的操作系统都支持POSIX功能,但Windows不支持。但是,根据Windows上的编译器的不同,您可能仍然具有名为ftruncate的函数,因为Windows上的C运行时经常尝试伪造POSIX功能的子集-其中许多伪造都是不可靠的,但是我坦白地说,鉴于Windows正确的确实具有等效的原始操作,因此我看不出如何ftruncate会搞砸,它只是具有不同的名称(SetEndOfFile)。

相关问题