I'm writing a C program that will open a file, write to it, and then read what was written. I can open, write, and close the file, but I can't read the lines and parse them correctly.
I have read many other blogs and sites, but none fully address what I'm trying to do. I've tried adapting their general solutions, but I never get the behavior I want. I have run this code with fgets(), gets(), strtok(), and scanf(), and fscanf(). I used strtok_r() as it was recommended as best practice. I used gets() and scanf() as experiments to see what their output would be, as opposed to fgets() and fscanf().
What I want to do:
- get first line // fist line is a string of space delimited ints "1 2 3 4 5"
- parse this line, convert each char number into a integer
- store this into an array.
- get the next line and repeat until EOF
Can someone please tell me what I'm missing and what functions would be considered best practice?
Thanks
My code:
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int main(){
FILE * file;
// read data from customer.txt
char lines[30];
file = fopen("data.txt", "r");
// data.txt currently holds five lines
// 1 1 1 1 1
// 2 2 2 2 2
// 3 3 3 3 3
// 4 4 4 4 4
// 5 5 5 5 5
char *number;
char *next = lines;
int s = 0;
int t = 0;
int num;
int prams[30][30];
while(fgets(lines, 30, file)){
char *from = next;
while((number = strtok_r(from, " ", &next)) != NULL){
int i = atoi(number);
prams[t][s] = i;
printf("this is prams[%d][%d]: %d\n", t, s, prams[t][s]);
s++;
from = NULL;
}
t++;
}
fclose(file);
}// main
expected output:
this is prams[0][0]: 1
...
this is prams[4][4]: 5
Actual output:
this is prams[0][0]: 1
this is prams[0][1]: 1
this is prams[0][2]: 1
this is prams[0][3]: 1
this is prams[0][4]: 1
program ends