たとえば、「これはtxtファイルです」(この内容は可変である可能性があります)を含むfile.txtがあり、file.txtを読み取ってその内容をchar *に保存する関数が必要です。
file.txt の内容 -> 「これは .txt ファイルです」
「これは .txt ファイルです」を含む char *readedContent が必要です。
最初に、char *str (str には "this is a .txt file" が含まれています) の内容を "file.txt" に保存し、次にこのファイルから文字列を取得しようとしましたが、文字列には "This .txt ファイルです」。(スペースや @,? などの文字を追加することがよくあります)
私の機能は次のとおりです。
char *special_char_remplace(char *str){
FILE *f1;
f1 = fopen("file.txt","w+");
fprintf(f1,"%s", str);
fclose(f1);
size_t len, bytesRead;
char *readedContent;
FILE* f2;
f2 = fopen("file.txt", "rb");
fseek(f2, 0, SEEK_END);
len = ftell(f2);
rewind(f2);
readedContent = (char*) malloc(sizeof(char) * len + 1);
readedContent[len] = '\0'; // Is needed only for printing to stdout with printf
bytesRead = fread(readedContent, sizeof(char), len, f2);
printf("STRING: %s\n", readedContent);
fclose(f2);
return readedContent;
}
私が抱えている問題は、char *readedContent に file.txt のコンテンツよりも多くの文字があることです。
どうもありがとう。