sobota, 13. april 2013

The best way to read a file (C)

C programming language has plenty options on how to read a file. We will use the standard function fscanf. See an example:

Determine the pointer to a file using FILE variable and fopen function.

FILE *f = fopen(<path of the file>);

Or if you are reading through the arguments just simply change the path to argv[i], where i represents the index of the input argument e.g: ./a.out file.txt -> fopen(argv[2]);

Now you need to do a simple buffer. If you are reading characters simply create new char variable. Do the same with other variables. In this case I am going to use integer variable - I am going to read numbers off the file.

int buffer = 0;

Thats it! We are now ready to read the file. See the following code on how to read it:

fscanf(f, "%d", buffer);
fscanf(f, "%s", buffer); <- if your buffer is char variable 

Voila. You can now use the feof(f) function which closes the reading stream when the end of file appears.

Ni komentarjev:

Objavite komentar