Jump to content




Recent Status Updates

View All Updates

Binpress - Cut your development time and costs in half
Photo
- - - - -

Reading And Writing Files In C

hello world read write file

  • Please log in to reply
40 replies to this topic

#1 Guest

Guest

    CC Devotee

  • Expert Member
  • PipPipPipPipPipPip
  • 914 posts
  • Location:USA
  • Programming Language:C, Java, Python, Bash, Others
  • Learning:Assembly, Scheme

Posted 03 November 2009 - 07:57 PM

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

Dynamic Arrays: Using malloc() and realloc()

 

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>

 

Difference between c and c++


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 */
}

 

Getter and Setter Methods


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.

 

Looking for more beginner tutorials in C?

A simple TCP server using Linux C API

Basic C, for beginners!

Switch and cases in C


Edited by Roger, 26 February 2013 - 03:57 PM.

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

#2 John

John

    CC Mentor

  • Moderator
  • 4,450 posts
  • Location:New York, NY

Posted 03 November 2009 - 08:55 PM

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?
  • 0

#3 Guest_Jordan_*

Guest_Jordan_*
  • Guest

Posted 04 November 2009 - 05:12 AM

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

#4 WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderator
  • 16,924 posts
  • Location:Upstate, South Carolina
  • Programming Language:C, C++, PL/SQL, Delphi/Object Pascal, Pascal, Transact-SQL, Others
  • Learning:Java, C#, PHP, JavaScript, Lisp, Fortran, Haskell, Others

Posted 04 November 2009 - 08:40 AM

short and sweet. +rep
  • 0
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

#5 so1i

so1i

    CC Addict

  • Advanced Member
  • PipPipPipPipPip
  • 297 posts

Posted 04 November 2009 - 10:48 AM

This is good, well structured. +rep
  • 0

#6 Guest

Guest

    CC Devotee

  • Expert Member
  • PipPipPipPipPipPip
  • 914 posts
  • Location:USA
  • Programming Language:C, Java, Python, Bash, Others
  • Learning:Assembly, Scheme

Posted 04 November 2009 - 06:19 PM

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.

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

#7 marwex89

marwex89

    CC Mentor

  • VIP Member
  • PipPipPipPipPipPipPipPip
  • 2,857 posts

Posted 08 November 2009 - 10:20 AM

+rep for the tut, you beggar :P
  • 0
Hey! Check out my new Toyota keyboaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

#8 debtboy

debtboy

    CC Devotee

  • Just Joined
  • PipPipPipPipPipPip
  • 499 posts

Posted 08 November 2009 - 12:08 PM

Great tutorial +rep

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

  • 0

#9 Guest

Guest

    CC Devotee

  • Expert Member
  • PipPipPipPipPipPip
  • 914 posts
  • Location:USA
  • Programming Language:C, Java, Python, Bash, Others
  • Learning:Assembly, Scheme

Posted 08 November 2009 - 02:38 PM

Thanks everyone :D
  • 0
Root Beer == System Administrator's Beer
Download the new operating system programming kit! (some assembly required)

#10 tonymorrison39

tonymorrison39

    CC Newcomer

  • Just Joined
  • PipPip
  • 20 posts

Posted 21 November 2009 - 08:46 AM

very nice i learned something
  • 0

#11 arkanion

arkanion

    CC Newcomer

  • Just Joined
  • PipPip
  • 10 posts

Posted 13 January 2010 - 12:00 PM

nice issue
  • 0

#12 Phineas

Phineas

    CC Newcomer

  • Just Joined
  • PipPip
  • 11 posts

Posted 13 January 2010 - 03:27 PM

Nice TuT.
  • 0





Also tagged with one or more of these keywords: hello world, read, write, file

Powered by binpress