テキスト ファイルへの文字列の書き込みとファイルからの読み取りに問題があります。
入力文字列 ( char text1
) がファイル ( input.txt
) に正しく書き込まれ、読み取られます。しかし、結果ファイルに問題があります。文字列はファイルに正しく書き込まれているようですが、ファイルを見ると、ファイルの最初の結果文字列の前に空白があります。テキスト " weather is weather
" を入力すると、結果ファイルには " weather is is weather
" が含まれます。結果の文字列テキストは問題ありません。唯一の問題は、何らかの理由で結果ファイルの先頭に空白があることです。
このコードで結果ファイルの内容を画面に出力すると
while((ch2 = fgetc(result)) != EOF)
printf("%c", ch2);
何も出力しませんが、text2
(ファイルからではなく) 文字列自体をputs(text2);
出力すると、正しく出力されます。
この問題の原因は何ですか?どうすれば解決できますか?
プログラム全体は次のとおりです。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char text1[200], text2[200], words[20][100], *dist, ch1, ch2;
int i, j, nwords=0;
FILE *input, *result;
input = fopen("input.txt", "w");
if(input == NULL)
{
perror("Error opening the file.\n");
exit(EXIT_FAILURE);
}
// Text input
printf("\n Enter the text:\n\n ");
gets(text1);
fputs(text1, input);
fclose(input);
// Split string into words
dist = strtok(text1, " ,.!?");
i=0;
while(dist!=0)
{
strcpy(words[i],dist);
dist = strtok(NULL, " ,.!?");
i++;
nwords++;
}
// Duplicating words that doesn't repeat in input string and copy them into tex2 string
int flag_arr[20];
memset(flag_arr, 0, 20);
for(i=0; i <= nwords-1; i++)
{
for(j=0; j<=nwords-1; j++)
{
if(strcmp(words[i],words[j])==0)
{
flag_arr[i] += 1;
}
}
}
for(i = 0; i <=nwords-1; i++)
{
if(flag_arr[i] > 1)
{
strcat(text2," ");
strcat(text2,words[i]);
}
else
{
strcat(text2," ");
strcat(text2,words[i]);
strcat(text2," ");
strcat(text2,words[i]);
}
}
result = fopen("result.txt", "w");
if(result == NULL)
{
perror("Error opening the file.\n");
exit(EXIT_FAILURE);
}
fputs(text2, result);
fclose(result);
// Rezultats
fopen("input.txt", "r");
if(input == NULL)
{
perror("Error opening the file.\n");
exit(EXIT_FAILURE);
}
fopen("result.txt", "r");
if(result == NULL)
{
perror("Error opening the file.\n");
exit(EXIT_FAILURE);
}
printf("\n\n\n Input:\n\n ");
while((ch1 = fgetc(input)) != EOF)
printf("%c", ch1);
// puts(input);
printf("\n\n\n Result:\n\n ");
while((ch2 = fgetc(result)) != EOF)
printf("%c", ch2);
// puts(text2);
fclose(input);
fclose(result);
getchar();
return 0;
}