Jump to content

Reading And Writing Files In C

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
39 replies to this topic

#1
Guest

Guest

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 3,414 posts
This tutorial will show you how to read and write files in C.
All file functions need <stdio.h> to work properly.

The first thing you need to know about is file pointers. File pointers are like any other pointer, but they point to a file. (Kind of obvious). You define a file pointer as follows:
FILE *filepointer;
In order to make the file pointer point to a file you use the fopen function. The function works as follows:
filepointer=fopen("filename", "mode");
fopen returns a file pointer. It returns NULL if the file does not exist.
fopen takes the first argument as the filename to open. It needs to be a string.
The second argument is the mode argument
Mode specifies what you want to do with the file.
Some modes are:
  • "r" - read the file
  • "w" - write the file
  • "a" - append to the file
  • "r+" - read and write to the file
  • "w+" - read and write, overwrite the file
  • "a+" - read and write, append
These modes will open files in text mode. Files opened in text mode have some bytes filtered out. If you want to open binary files use binary mode by adding a "b" to the mode. For example:
  • "rb" - read the file in binary mode

There are three input and output streams that are automatically open whenever your program starts. These are stdin, stdout and stderr.
These file pointers work as follows:
  • stdin: opened in read ("r") mode, this file pointer reads from standard input. Any input that you provide on the command line is read by stdin.
  • stdout: opened in write ("w") mode, this file pointer writes to the standard output. Anything written to this stream is printed on the command line.
  • stderr: opened in write ("w") mode, this file pointer writes to the standard error. This is generally meant for error messages that are produced by your program. Whatever is written to this stream is usually printed on the command line like stdout. In most operating systems, there are ways to tell whether output was sent to stdout or stderr.

To read a character from a file, you use fgetc. It is like getchar, but for any file, not just stdin.
It works like this:
character=fgetc(filepointer);
fgetc returns the character that is read from the file as an integer.
fgetc takes the file pointer as its only input.
It will automatically increment the pointer to read the next character.

fputc allows you to write a character to a file:
fputc(character, filepointer);
fputc takes an unsigned char as the first argument and the file pointer as the second argument.
fputc returns EOF when it reaches the end of file. EOF is a constant defined in <stdio.h>

You can also use fprintf and fscanf. They work like printf and scanf, except the file pointer is the first argument. They work like this:
fprintf(filepointer, "Hello, World!\n"); //write hello world to the file
fscanf(filepointer, "%d", integer); //read an integer from the file
In order to close the file again, you must use fclose. It looks like this:
fclose(filepointer);
fclose closes the file that filepointer points to.

For example, if you want to print the contents of data.txt the code could look something like this:
#include <stdio.h>

int main()
{
	FILE *filepointer;
	int character;
	filepointer=fopen("data.txt", "r"); /* filepointer points to data.txt */
	if (filepointer==NULL) { /* error opening file returns NULL */
		printf("Could not open data.txt!\n"); /* error message */
		return 1; /* exit with failure */
	}
	/* while character is not end of file */
	while ((character=fgetc(filepointer)) != EOF) {
		putchar(character); /* print the character */
	}
	fclose(filepointer); /* close the file */
	return 0; /* success */
}

There are also fputs and fgets. fputs is simple, similar to puts. Unlike puts, it does not automatically append a newline to supplied string. It writes a line to a file like so:
fputs("string\n", filepointer);
fgets is a special function in C. It is regarded as the best function in standard C to reliably accept input. Functions like scanf have undefined behavior when given erroneous input. Programs that use scanf or gets can have buffer overflows and be susceptible to exploits! scanf can be nice for those just starting to learn C, but it should never be used in real-world code.
fgets usage looks like this:
char input[100];
fgets(input, sizeof(input), filepointer);
The middle argument is the beauty of fgets. It is the limit of characters that fgets will store in the char array. Usually sizeof(firstargument) is a good idea, unless you are allocating memory with malloc or a similar function.
fgets reads as much as it can. If the input goes over the limit, it will stop. The next file-reading function will continue where fgets left off. (Many times, fgets again, in a loop)
fgets does not discriminate. It reads spaces and newlines with the rest of the input.
fgets returns NULL when nothing can be read. (end of file)
Here's an example very similar to the one above, but instead of fgetc, it uses fgets and fputs:
#include <stdio.h>

int main()
{
	FILE *filepointer;
    char string[100];
	filepointer=fopen("data.txt", "r"); /* filepointer points to data.txt */
	if (filepointer==NULL) { /* error opening file returns NULL */
		printf("Could not open data.txt!\n"); /* error message */
		return 1; /* exit with failure */
	}
	/* while we're not at end of file */
	while (fgets(string, sizeof(string), filepointer) != NULL) {
	    fputs(string); /* print the string */
	}
	fclose(filepointer); /* close the file */
	return 0; /* success */
}

That's it! If you have questions, comments or suggestions feel free to post! +rep is very appreciated.

Edited by Guest, 13 April 2012 - 10:59 PM.

Root Beer == System Administrator's Beer
Download the new operating system programming kit! (some assembly required)

#2
John

John

    Writes binary right handed and hex left handed

  • Moderators
  • 6,321 posts
Nice tutorial. One thing I never fully took the time to understand is the other modes. Technically, aren't there 12 modes? r, w, a, r+, w+, a+ and then all those in binary mode? I never understood the difference between x, x+, and xb - could you elaborate on those?

#3
Guest_Jordan_*

Guest_Jordan_*
  • Guests
Nicely done, I've already referred a new member to this tutorial. :)
+rep

#4
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
short and sweet. +rep
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

#5
so1i

so1i

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 312 posts
This is good, well structured. +rep

#6
Guest

Guest

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 3,414 posts

John said:

Nice tutorial. One thing I never fully took the time to understand is the other modes. Technically, aren't there 12 modes? r, w, a, r+, w+, a+ and then all those in binary mode? I never understood the difference between x, x+, and xb - could you elaborate on those?

I have added the x+ file modes to the list, but I am not really sure what binary mode does. I will look into it.
Edit: I have researched it and added binary mode to the tutorial.

Edited by Guest, 04 November 2009 - 07:47 PM.

Root Beer == System Administrator's Beer
Download the new operating system programming kit! (some assembly required)

#7
marwex89

marwex89

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 10,720 posts
+rep for the tut, you beggar :P
Hey! Check out my new Toyota keyboaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

#8
debtboy

debtboy

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 916 posts
Great tutorial +rep

Edited by debtboy, 10 November 2009 - 02:14 PM.


#9
Guest

Guest

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 3,414 posts
Thanks everyone :D
Root Beer == System Administrator's Beer
Download the new operating system programming kit! (some assembly required)

#10
tonymorrison39

tonymorrison39

    Newbie

  • Members
  • PipPip
  • 20 posts
very nice i learned something

#11
arkanion

arkanion

    Newbie

  • Members
  • PipPip
  • 10 posts
nice issue

#12
Phineas

Phineas

    Newbie

  • Members
  • PipPip
  • 11 posts
Nice TuT.