Trying to read a two numbers from a text file

447 Views Asked by At

I am trying to read two numbers from a text file. I used strtok, and the delimiter is " ". The text file (named data.txt) file has only two numbers, the line is "3 5". But the program crashes... any help is appreciated.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
    
int main(){
    
    FILE *data;
    data = fopen("data.txt", "r");
    
    int m, n;
    char *line, *number;
    while(!feof(data))
    {
        fscanf(data, "%s", line);
        number = strtok(line, " ");     
        m = atoi(number);       
        number = strtok(NULL, " ");     
        n = atoi(number);
    }       
}
1

There are 1 best solutions below

4
On

line is a uninitialized pointer, it doesn't point to any valid memory location so you can't use it to store data, use an array instead.

while(!feof(data)) is not what you'd want to use to control your read cycle.

Use fgets/sscanf to parse the values, simple and easy way to do it:

FILE *data;
data = fopen("data.txt", "r");
int m, n;
char line[32];

if (data != NULL)
{
    while (fgets(line, sizeof line, data)) // assuming that you want to have more lines
    {
        if(sscanf(line, "%d%d", &m, &n) != 2){
            // values not parsed correctly
            //handle parsing error
        }
    }
}

Or as @chux pointed out, to detect extra junk on the line:

 char end;  
 if(sscanf(line, "%d%d %c", &m, &n, &end) != 2) {
     // if more characters exist on the line
     // the return value of sscanf will be 3
 }

If the values in the file can be outside the range of an int consider using strtol instead of sscanf.