このプログラムでは、私の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()
メモリ内のファイルを読み込んで内容を変更するにはどうすればよいですか? – Jack
おそらく、配列と動的メモリ割り当て( 'malloc/free')を使う必要があります。あなたが言語についてもっと学ぶまでは、2ファイル法を使う方が簡単かもしれません。そうすれば、一度に1行分のテキストを処理するだけで済みます。 –