
Thank you and I loooooooooooooove you for this. First year student at university with no programming experience looking for something like this to process some files for an assignment. mechanical engg, u tutorial helped me much in obtaining output file in txt format, thank a lot for ur help Why not let us know what you think by adding your own comment! There are currently 31 responses to “C Tutorial – File I/O (using text files)” But you have to be sure that the file is perfectly formatted or fscanf will not handle it correctly). (It is also possible to make use of the library function fscanf. Then the fgets library functions can be used to read the contents of the file. If you want to read a file you have to open it for reading in the read (r) mode. (If there are a lot of files open but not closed properly, the program will eventually run out of file handles and/or memory space and crash.) File I/O: reading a text file But the close function does not close the files correctly. You have to be careful that you don’t type “close” instead of “fclose”, because the close function exists. This command must be given, especially when you are writing files. The fclose statement will close the file. The only new thing is that it uses the file pointer as its first parameter. It can be almost used in the same way as printf. The fprintf statement should look very familiar to you. This for loop will count to ten, starting from one. (Indicating that something has gone wrong). If the fopen was not successful, the program will return a one. The if statement after de fopen, will check if the fopen was successful.

If the file cannot be opened (for some reason) the variable ptr_file will contain NULL. The fopen command returns a pointer to the file, which is stored in the variable ptr_file. But you must be careful! If the file exists, it will be destroyed and a new file is created instead. If the file does not exist it will be created. The fopen statement opens a file “output.txt” in the write (w) mode. So let’s take a look at the example: ptr_file =fopen(“output”, “w”)
