0

None of fgets() and fscanf() works, the file.txt has

100
6 0060001
6 4321298
3 5001
6 0604008
6 0102111

My code reads the first integer pretty well but the not the 7 digit number? Any help?

int main(void)
{
    int numTotal = 0;
    int maxShy = 0;
    char temp[101];
    char ch;
    char * ptr;
    int count = 0;

    FILE *fp1 = fopen("file.txt", "r+");
    FILE *fp2 = fopen("output", "w");

    // read the first line, set the total number
    while ((ch = fgetc(fp1)) != '\n')
    {
        temp[count] = ch;
        count++;
    }
    temp[++count] = '\0';
    count = 0;
    numTotal = strtol(temp, &ptr, 10);
    printf("%d", numTotal);


    for (int i = 0; i < numTotal; i++)
    {
        // This part works fine
        fscanf(fp1, "%d", &maxShy);
        printf("%d ", maxShy);

        // This part doesn't outputs a different 7 digit number from 0060001 and others
        fscanf(fp1, "%s", temp);
        printf("%s\n", temp);
    }

    fclose(fp1);
    fclose(fp2);


    system("pause");
    return 0;
}
R Sahu
  • 204,454
  • 14
  • 159
  • 270
TPWang
  • 1,322
  • 4
  • 20
  • 39
  • what is the output ?? – Karthikeyan.R.S Apr 11 '15 at 04:26
  • this line: 'temp[++count] = '\0';' leaves a garbage character before the '\0' byte. suggest removing the '++' – user3629249 Apr 11 '15 at 04:39
  • this line: 'fscanf(fp1, "%s", temp);' will read nothing as the input will contain a space character. suggest: 'fscanf(fp1, " %s", temp);' Note the leading space in the format string. a space in a format string will skip over white space, like the space between the two values – user3629249 Apr 11 '15 at 04:45
  • The out put was Assertion Failure, and something to do with the String. – TPWang Apr 12 '15 at 05:52

1 Answers1

1

Instead of

temp[++count] = '\0';

you need

temp[count] = '\0';

since you are incrementing count in the while loop.

Also, the first line indicates that 100 lines of text are expected. However, you only have 6 more lines of text. Nothing is read after that. Add checks to make sure that you stop when reading fails.

Instead of:

fscanf(fp1, "%d", &maxShy);

Use

if ( fscanf(fp1, "%d", &maxShy) != 1 )
{
   break;
}

Similarly, use:

if ( fscanf(fp1, "%s", temp) != 1 )
{
   break;
}
R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • Thank you, also I only pasted the first 6 lines of the text file. I should try to change the count. – TPWang Apr 12 '15 at 05:54