0

I'm trying to write a program where I add words to one text file. Also, I can delete any word from this file and I save the result without this word to another text file. But when I run it, my second text file is filled with H symbols, and its size can be more than 100 mb. What's wrong with this code? Here it is:

int main(void)
{   
int wordNumbers;
int i;
char buf[512];
char word[128];

FILE *o_file = fopen("C:\\atest.txt", "a");
FILE *s_file = fopen("C:\\btest.txt", "w");

printf("please add an amount of words of the dictionary ");
scanf("%i", &wordNumbers);

for (i=0; i< wordNumbers; i++)
{   char word[100] = {0};
    printf("add a word into the dictionary please\n");
    scanf("%s", &word);
fprintf(o_file, "%s\n", word);
}

if(!o_file || !s_file) return -1;
printf("please write down the word you want to delete\n");
scanf("%s",&word);
do    
 {  
    fscanf(o_file, "%511s", buf);
    if(!strcmp(buf, word))
        continue;
    fprintf(s_file, "%s\n", buf);
}
while(!feof(o_file));
fclose(o_file);
fclose(s_file);

   }    
donjuedo
  • 2,475
  • 18
  • 28

1 Answers1

2

You print to the file o_file to insert your strings. Then, immediately after this, you start to read from this same file.

Read and write to a single file both use the same file pointer. Because the file pointer is here always at the very end of the file after these writes, the next read should fail – but since you don't check the result of fscanf, you don't ever realize that, and you write uninitialized data into the new file.

  1. After writing the new contents into o_file, reset the file pointer to the start with fseek (o_file, 0, SEEK_SET) or rewind (o_file).
  2. Always test if fscanf (and scanf) returns the correct number of recognized items. The return value is there for a reason.
  3. Also read Why is “while ( !feof (file) )” always wrong?.
Community
  • 1
  • 1
Jongware
  • 22,200
  • 8
  • 54
  • 100