Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read int values from a text file in C

I have a text file that contains the following three lines:

12 5 6 4 2 7 9 

I can use the fscanf function to read the first 3 values and store them in 3 variables. But I can't read the rest. I tried using the fseek function, but it works only on binary files.

Please help me store all the values in integer variables.

like image 840
elh mehdi Avatar asked Jan 05 '11 04:01

elh mehdi


People also ask

How do you read integers from a file in C?

We use the getw() and putw() I/O functions to read an integer from a file and write an integer to a file respectively. Syntax of getw: int num = getw(fptr); Where, fptr is a file pointer.

Which function returns the integer value in file handling?

putw(), getw() functions are file handling function in C programming language which is used to write an integer value into a file (putw) and read integer value from a file (getw).

What is the text file in C?

Text files in C are straightforward and easy to understand. All text file functions and types in C come from the stdio library. When you need text I/O in a C program, and you need only one source for input information and one sink for output information, you can rely on stdin (standard in) and stdout (standard out).


2 Answers

A simple solution using fscanf:

void read_ints (const char* file_name) {   FILE* file = fopen (file_name, "r");   int i = 0;    fscanf (file, "%d", &i);       while (!feof (file))     {         printf ("%d ", i);       fscanf (file, "%d", &i);           }   fclose (file);         } 
like image 149
Vijay Mathew Avatar answered Sep 21 '22 15:09

Vijay Mathew


How about this?

fscanf(file,"%d %d %d %d %d %d %d",&line1_1,&line1_2, &line1_3, &line2_1, &line2_2, &line3_1, &line3_2);  

In this case spaces in fscanf match multiple occurrences of any whitespace until the next token in found.

like image 43
MAK Avatar answered Sep 25 '22 15:09

MAK