【问题标题】:How do I write to a specific line of file in c?如何在c中写入特定的文件行?
【发布时间】:2014-05-18 16:58:55
【问题描述】:

所以我有一个我正在做的项目,我创建了一个允许用户写入文件的程序,如下所示:

 #include <stdio.h>
 #include <stdlib.h>

 FILE *fd;
 FILE *fw;

     struct store
     {
          char Word[512];
          char NWord[512];
     }
     stock;

     struct store2
     {
          char Definition[512];
     }
     stock2;

char done='y';
int count=1;
int c=0;
int d=0;

int main(void)
{
    fw=fopen("Test Z W.txt","w");
    fd=fopen("Test Z D.txt","w");

    do
    {    
         printf("Word %d: ",count);
         gets(stock.Word);
         while((c= getchar()) != '\n' && c != EOF);

         printf("Definition %d: ",count);
         gets(stock2.Definition);
         while((c= getchar()) != '\n' && c != EOF);  

         fprintf(fw,"%s\n", stock.Word);         
         fprintf(fd,"%s\n", stock2.Definition);        
         count=count+1;  
         system("cls");                
    }
    while (count<11);

fclose(fd);
fclose(fw);

return 0;

}

这段代码很好,但是,我想扩展它,以便可以选择只编辑一个选定的行,而不是擦除整个文件并再次写入所有内容。

我要做的就是使用 How do you write to a specific line of a txt file in C?

这不是很有帮助,因为我无法获取答案并将其导入我的代码,无论哪种方式,我所需要的只是可以轻松修复如下错误的东西。

 1
 2
 Three
 4
 5
 6
 7
 8
 9
 10

将自动询问用户他们想要编辑哪一行。

【问题讨论】:

  • 文件不是字符串列表,它们是字符列表。您不能轻易地用较短或较长的字符串“替换”单个字符串。如果您不想重写整个文件,则需要一个故障安全系统来在修改后读取/重写所有内容。这比简单地重写整个文件要困难得多(而且容易出错)。
  • 之前的回答是没有用的,因为你想做的事情在今天基本上和当时一样不可能。
  • 问题是我不能要求一个词并且改变它,它必须是一行。
  • 那么,为什么明显的答案(重写文件)也是一个问题?
  • 是的,这几乎你必须做的。文件系统中没有魔法可以让你说“我想把这一行放在中间,你介意扩展文件并为我把它后面的所有东西都推下来吗?”你必须自己做。 @MrSykkox,即使在他寻找之后,如果新行的长度与他要替换的长度不同,他将覆盖旧行或留下一些奇怪的间隙。

标签: c string file text structure


【解决方案1】:
#include <stdio.h>
int main()
{
    FILE *fp,*fc;
    int lineNum;  //stores line number which should be edited.
    int count=0;  //count number lines in source file.
    int ch;   //temporary place to store character of source file(one at a time).
    int edited=0;  //0=false and 1=true
    int t;   //temporary place to store input which you want to be replaced with error in text file.


    fp=fopen("source.txt","r");
    fc=fopen("target.txt","w");

    if(fp==NULL||fc==NULL)
    {
        printf("\nError...cannot open/create files");
        return 1;
    }

    printf("\nEnter Line Number Which You Want 2 edit: ");
    scanf("%d",&lineNum);

    while((ch=fgetc(fp))!=EOF)
    {
        if(ch=='\n')  //counts number of lines
            count++;
        if(count==lineNum-1 && edited==0)  //if specific line(error line) is found and that line is still not edited. More Explanation:- If we want to edit 3rd line than we should start writing at the end of 2nd line(hence count==lineNum-1) and edited==0 means that error line is still not edited. 
        {
            printf("\nEnter input to store at line %d:",lineNum);

            scanf(" %c",&t);  //You can replace this statement with any input operation which you want to replace it with the error line.

            if(count==0)  //if its the first line to edit..
                fprintf(fc,"%s\n",t)   //watch closely,no '\n' before %s,This will copy without creating a extra newline in beginning of new file.
            else 
                fprintf(fc,"\n%s\n",t);  //stores input at error line in file fc(target.txt) from variable t.

            edited=1;  //this prevents loop to execute more than once(as error is already edited),so there will be no need to execute this loop till the end of program

            while( (ch=fgetc(fp))!=EOF )  //Actually this loop will skips the existing line in source.txt(see below)
            {                           //we want to skip this line because this is error line.
                if(ch=='\n')//this will break when next new line(after error line is skipped) is found.
                    break;
            }
       }
       else
          fprintf(fc,"%c",ch);
    }
    fclose(fp);
    fclose(fc);

    if(edited==1)
        printf("\nCongrates...Error Edited Successfully.");
    else
        printf("\nLine Not Found");

return 0;
}

这个程序会打开一个源文件(可能有错误,我把它叫做source.txt*)并继续逐个字符地读取它并写入新文件(target.txt)直到( EOF)被找到。但它会停在特定的行,并会要求用户输入一些数据,这些数据将在新的文本文件(target.txt)中代替错误(源文件中的错误行)写入。

所以最后你会得到没有错误的 target.txt 文件。打开并检查。

在这个程序中,我假设我们只想替换第 3 行的单个字符。但是您可以更改此操作以将其替换为字符串、浮点数或整数等。

这是输出:-

输入您想要的行号 2 编辑:3

在第 3 行输入要存储的输入:3

恭喜...错误编辑成功。

target.txt的内容:-

1

2

3

4

5

6

7

【讨论】:

  • 谢谢,我猜我必须使用另一个函数将目标的内容复制回源?
  • 我已经告诉过你,你可以用你想要的任何输入操作替换这些行。如果你想把 3 改成“三”,你必须添加scanf(" %s[^\n]",t);(这里 t 应该是一个字符串数组),你也应该添加这个fprintf(fc,"\n%s\n",t);
  • No 不要复制回源,一切完成后,只需删除原始文件(srouce.txt)并将 target.txt 重命名为 source.txt....:)
  • 我想我会详细说明,运行上述程序后,您已经有了一个无错误的 source.txt(target.txt) 副本。那你为什么要把target.txt的所有内容都复制到source.txt呢?你能做的就是删除source.txt文件,把target.txt重命名为source.txt。就是这样,现在您将拥有一个名为 source.txt 的文件(无错误)。
  • 我修复了字符输入,意识到我必须将 int 更改为 char。无论如何,我应该更具体一点:我需要能够在循环中使用它,因此将新版本粘贴回旧版本使这项工作没有问题。我只是将“目标文件”用作临时替代品。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多