如何在C语言中在文件的不同位置编写字符串

时间:2015-06-26 20:17:02

标签: c file-io

在下面的代码中:

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char const *argv[])
{
    FILE *fp ;
    fp = fopen("out.txt", "r+");
    int count = 1;
    char ch ;
    char userInput[5] ;
    int lineNumber = 0;
    while (lineNumber!= -1){
        fgets(userInput, sizeof(userInput), stdin);
        lineNumber = atoi(userInput);
        while((ch=fgetc(fp))!=EOF)
        {
            if(ch=='\n')  //counts number of lines
                count++;
            if(count == lineNumber)
            {
                fprintf(fp, "writed %d\n", count);
                fseek(fp, 0, SEEK_SET);
            }

        }
    }
    return 0;
}

我想在用户给我的行中写一个字符串,我将用户答案存储在userInput中,然后将其转换为int并将其存储在lineNumber中。 当我尝试在第90行编写前例(我的文件有100行)时,我得到两个错误: 1.文件缩小为91行文件(保留100行) 2.尽管我寻求第一个文件,在下一个循环和用户输入中不再写入行。

1 个答案:

答案 0 :(得分:1)

读取文件(计算其行数),然后转身并写入它是很棘手的。除此之外,你必须在阅读和写作之间做fseek 之类的事情。因此,请尝试更改fseekfprintf调用的顺序:

fseek(fp, 0, SEEK_SET);
fprintf(fp, "writed %d\n", count);

另外,请注意,除非您正在编写的新文本(“writed ###”)与完全的长度与之前的任何行相同,否则其余的行结构该文件可能会出现乱码。

另请参阅this question中的C FAQ list