2017-04-30 3 views
0

このプログラムでは、私のedit()関数が正しく動作しません。何かを書き込もうとすると、内容全体が消去され、appendText()に1つの単語しか追加されません。ファイル?なぜfputs()はファイル内に単語を1つだけ追加しますか?

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



main(void){ 

    char fName[100]; 

    printf("Enter file name :\n"); 
    scanf("%s",&fName); //File Name 

    int choice; 
    printf("Enter your choice : \n1.Edit text\n2.Read the contents of the file\n3.Append text\n4.Exit\n"); //Enter choice 
    scanf("%d",&choice); 

    switch(choice){ 

     case 1 : 
      edit(fName);  //Edit text 
      break; 
     case 2 : 
      readContents(fName); //Read file  
      break; 
     case 3 : 
      appendText(fName);  //Append 
      break; 
     case 4 : 
      exit(0);   //Exit 
      break; 
     default : 
      printf("Invalide Option!\n"); 
      break;  
    }//End switch 

}//End main 

//Function to edit contents of the file 
void edit(char file[100]){ 

    int line,temp = 0; 
    printf("Enter the line no. to be edited : \n"); 
    scanf("%d",&line); //Line no 

    char sentence[100]; 
    printf("Enter the content : \n"); 
    scanf("%s",sentence); 

    char str[100]; 
    FILE *fName = fopen(file,"w"); 

    while(!feof(fName)){ 

     temp++; 
     fgets(str,99,fName); 

     if(line == temp) 
      fputs(sentence,fName); break; 

    } 

    printf("\nContents of the file has been updated!\n"); 

    fclose(fName); 


}//End edit() 

//Function to read the contents of the file 

void readContents(char file[100]){ 

    char str[100]; 
    FILE *fName = fopen(file,"r"); 
    while(!feof(fName)){ 
     puts(fgets(str,99,fName)); 
    } 

    fclose(fName); 
    printf("\n"); 
} //End readContents() 


//Funtion to append string to an existing file 

void appendText(char file[100]){ 

    char str[100]; 
    FILE *fName = fopen(file,"a"); 

    printf("Enter your string :\n"); 
    scanf("%s",&str); 

    fputs(str,fName); 

    fclose(fName); 
    printf("\nText added to the file\n"); 


}//End of append() 

答えて

2

実際に行っている(テキスト)ファイルの内容を変更して1行を変更することはできません。新しい文字列を書き込むと、残りのファイルが上書きされます。ファイル全体をメモリに読み込んで、必要な行を変更し、ファイル全体に書き込む必要があります。または、ファイルから読み込み、各行を2番目のファイルに書き出し(見つかったときにテキストを置き換えて)、ファイルを削除または名前を変更します。最初に見つかった空白文字で停止

非空白任意の数の文字、:%S(強調鉱山)にhttp://www.cplusplus.com/reference/cstdio/scanf/からのappendTextとして

、。終了したヌル文字は、保存されたシーケンスの最後に自動的に追加されます。

つまり、appendのscanfは最初の単語のみを読み取るため、最初の単語のみが追加されます。

+0

メモリ内のファイルを読み込んで内容を変更するにはどうすればよいですか? – Jack

+1

おそらく、配列と動的メモリ割り当て( 'malloc/free')を使う必要があります。あなたが言語についてもっと学ぶまでは、2ファイル法を使う方が簡単かもしれません。そうすれば、一度に1行分のテキストを処理するだけで済みます。 –

1

このコードの多くの問題の1つは、モード"w"でファイルを開くと、はすべて既存の内容を消去するということです。それをしたくない場合は、代わりにモード"r+"を使用してください。

+0

私はまだそれが動作していないことを試みた – Jack

+0

私はそれが多くの問題の一つに過ぎないと言った。 – zwol

関連する問題