Home > Enterprise >  How to read in multiple data types in input file
How to read in multiple data types in input file

Time:10-08

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);
    }

CodePudding user response:

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.

  •  Tags:  
  • c
  • Related