2
Contributors
1
Reply
3
Views
5 Years
Discussion Span
Last Post by Mouche
0

You just need to open a file using fopen(), read in data using fgets() or fscanf(), and then close the file using fclose().

Here is a snippet showing how to read data from a file line by line:
Reading a File Line By Line

If you want to read in numerical values, you need use fscanf().

Here's part of an example of reading in 20 integers line by line into an array:

int fd;
int numbers[20];
int i = 0;
// Open file here using fd

while (fscanf(fd, "%d", &numbers[i]) != EOF) {
  printf("numbers[%d] = %d\n", i, numbers[i]);
  i++;
}

// Close file

Note: I don't use any error checking here. This only works if the file has integers separated by whitespace (spaces or newlines). You will want to check the return value of fscanf(). If it returns 0, then no match occurred. If you put an 'a' in the file of integers, fscanf() would continually fail to match and the program would be stuck in an infinite loop.

Also, you would want to make sure your buffer is large enough to hold all the data in the file. Perhaps you would want to stop reading once you reach your buffer size.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.