0

I'm working on an academic project that has input files with the format:

R
+1
...
...
...
-5
W

The first and last lines are always going to be R or W. How do I read in both the characters and integers? If it were just ints it would be this.

    inputFile = fopen(filename, "r");
    while (!feof (inputFile)){
        int lineValue;
        fscanf (inputFile, "%d", &lineValue);
        printf("curr line value is -> %d \n",lineValue);
    }
  • https://stackoverflow.com/questions/5431941/why-is-while-feoffile-always-wrong – user16217248 Oct 07 '22 at 19:02
  • 4
    Please see [Why is `while ( !feof (file) )` always wrong?](http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) Read each line as a string with `fgets` and analyse the string content using `sscanf` and its return value (which should be `1`. – Weather Vane Oct 07 '22 at 19:03
  • Do *not* use `scanf`. If you are having even a moments hesitation about how to solve this, you do not want to add the headaches than `scanf` will bring. Just avoid it. – William Pursell Oct 07 '22 at 19:13

1 Answers1

1

This example program reads a file line by line checking the content. It has minimal error feedback, which could be more informative.

#include <stdio.h>

int main (void)
{
    FILE *inputFile = fopen("test.txt", "rt");
    if(inputFile == NULL) {
        return 1;           // file failed to open
    }
    char buf[100];
    
    // first line
    if(fgets(buf, sizeof buf, inputFile) == NULL) {
        return 1;           // could not read first line
    }
    if(buf[0] != 'R') {
        return 1;           // first line data was invalid
    }
    
    // data lines
    while(fgets(buf, sizeof buf, inputFile) != NULL) {
        int val;
        if(sscanf(buf, "%d", &val) != 1) {    // was the conversion successful?
            break;
        }
        printf("%d\n", val);
    }
    
    // check last line was valid
    if(buf[0] != 'W') {
        return 1;          // last line data was invalid
    }
    
    puts("Success");
    return 0;
}

Input file

R
+1
-5
W

Program output

1
-5
Success

For simplicity, the program ignores closing the file. The idea is to show how to control the file reading.

Weather Vane
  • 33,872
  • 7
  • 36
  • 56