× Home
Next Lec → ← Previous Lec

File I/O in C

Why do we need a file?

Volatile VS Non-volatile memory

Volatile Memory

  • Volatile memory is computer storage that only maintains its data while the device is powered.
  • The RAM will hold data, programs, and information as long as it has a constant power supply but immediately the power is interrupted all that content is cleared.
  • The Volatile memory will only hold data temporarily.

Non Volatile Memory

  • Non-volatile memory is computer memory that can retain the stored information even when not powered.
  • This type of memory is also referred to as permanent memory since data stored within it can be retrieved even when there is no constant power supply.
  • It is used for the long-term storage of data.

Why do we need files?

  • When a C program is terminated, the data stored in ram is lost.
  • Storing in a file will preserve our data even after the program terminates.
  • RAM is not able to handle quite large amount of data due to its small size relative to the hard disk.
  • It is easy to transfer data as files.

Types of files

  • Text files→ stores data in plain text and these files can be opened by text editors. These are human readable
  • Binary files→ Here the data is stored as 0,1 stream that's why these files are secure and only computer can read these files.

File Operators in C

  • In C we can perform these high level operations on files:
    • 1→ Creating a new file
    • 2→ Opening a file
    • 3→ Closing a file
    • 4→ Reading from and writing to a file.

File I/O Functions in C

Working with files in C

  • When working with files, we have to declare a pointer of type fILE
    • FILE *ptr = NULL;
  • This declaration helps us to work with files through C program.

Opening a file - Creating or editing a file

  • stdio.h contains a function called fopen() for opening files in C.
  • The syntax for opening a file in standard I/O is:
    • ptr = fopen("fileopen","mode")
  • For Example:
    • fopen("E:\\Code\\harry.txt","w");
    • fopen("E:\\Programming\\bhai.bin","rb");
  • "r" → for reading
  • "w" → for writing over previously written text
  • "a" → for writing without removing previously written text in file
  • "r+" → for reading and writing
  • "rb" → read binary
                            
                            #include <stdio.h>
                             int main()
                             {
                                FILE *ptr=NULL; //this is a good practise
                                char string[34];
                                ptr = fopen("myfile.txt","r");
                                fscanf(ptr,"%s",string); //what this do is takes content till space or new line from
                                and store it to string variable
                                printf("Content of this file has :%s\n",string);
                                
                                return 0;
                             }
                            
                        

Output ↓
Content of this file has :this

Closing a file

  • If any file is opened in C program (using fopen()) it needs to be closed
  • Closing a file is accomplished by the library function fclose()
  • fclose(fptr); //fptr is the file pointer associated with the file to be closed

Reading a file

  • In order to read a file, we can use fscanf function.
  • This function is file version of scanf function.
  • fscanf expects a file pointer in addition to the other arguments with scanf expects.
  • We will have to open the file in read mode in order to use this function.

Writing to a file

  • In order to write to a file, we can use fprintf function.
  • This function is fiie version of printf function
  • fprintf expects a file pointer in addition to the other arguments which printf expects
  • We will have to open the file in write mode in order to use this function.
                            
                            #include <stdio.h>
                             int main()
                             {
                                FILE *ptr=NULL;
                                char string2 [100]="This content was produced by Tutorial64.c";
                                ptr = fopen("myfile.txt","w");
                                fprintf(ptr,"%s",string2); //inside the file this string will we inserted
                                //all the older text got removed and the text stored in string2 was inserted
                                // ptr = fopen("myfile.txt","a"); // in this mode the text inside string2 will be added he end to the file
                                
                                return 0;
                             }
                            
                        

More on file I/O

Working with files in C

  • stdio.h contains a function called fopen() for opening files in C
  • When working with files, we have to declare a pointer of type FILE
    • FILE * ptr;
  • This declaration helps us to work with files through C program
  • The syntax for opening a file in standard I/O is :
    • ptr = fopen("fileopen","mode")
  • In order to read/write to a file, we can use fscanf/fprintf function.
    • fscanf(fptr, "%s", buff);   fprintf(fptr, "Marks = %d", salary);
  • fclose(fptr); //fptr is the file pointer associated with file to be closed.

Mode & Description

Mode

Description

r

Opens an existing text file for reading

w

Opens a file for writing. If it doesn't exist, then a new file is created. Writing starts from the beginning of the file.

a

Opens a text file for writing in appending mode. If it does not exist, then a new file is created. The program will start appending content to the existing file content.

r+

This mode will open a text file for both reading and writting

w+

Opens a text file for both reading and writing. It first truncates the file to zero length if it exists, otherwise creates a file if it does not exist

a+

Opens a text file for both reading and writing. It creates the file if it does not exist. The reading will start from the beginning but writing can only append to file.

Other FILE I/O functions

  • As printf and scanf are used for printing and taking input from terminal
    • Same way fprintf and fscanf is used for taking input and output in files
  • There are various functions provided by C standard library to read and write a file, character by character, or in the form of a fixed length string
  • Some of them are:
    • fputc
    • fputs
    • fgetc
    • fgets

fputc function in C

  • Simplest function to write characters to a file in fputc
  • Syntax of fputc goes as follows:
    • in fputc (character, FILE pointer);
    • It returns the written character written on success.
    • On failure it returns EOF
      • End of File character
    • The EOF is a constant defined in the header file stdio.h
                                

                                #include <stdio.h>
                                 int main()
                                 {
                                    FILE *ptr = NULL;
                                    ptr = fopen("myfile2.txt","w"); // we have to open this in 'write' mode
                                    fputc('o',ptr);
                                    fclose(ptr);
                                    return 0;
                                 }
                                 
                            

fputs function

  • fputs function is used to write a null terminated string to a file in C
    • int fputs(const char *s, file *fp);
                                
                                #include <stdio.h>
                                 int main()
                                 {
                                    FILE *ptr = NULL;
                                    ptr = fopen("myfile2.txt","w"); // we have to open this in 'write' mode
                                    fputs("Harry is great",ptr);
                                    fclose(ptr);
                                    return 0;
                                 }
                                
                            

fgetc function

  • Simplest function to read characters from a file is fgetc
  • Syntax of fgetc goes as follows:
    • int fgetc(FILE * fp)
    • it returns the read character on success.
    • On failure it returns EOF
    • The EOF is a constant defined in the header file stdio.h.
                                
                                #include <stdio.h>
                                 int main()
                                 {
                                    FILE *ptr = NULL;
                                    ptr = fopen("myfile2.txt","r");
                                    char c = fgetc(ptr);
                                    printf("The character I got was : %c\n",c);
                                    fclose(ptr);
                                    return 0;
                                 }
                                
                            

fgets function

  • fgets function is used to write a null terminated string to a file in C
    • int fgets(const char *s, int n, FILE *fp)
      • int n → the number of character we wanted to get from the file
                                
                                #include <stdio.h>
                                 int main()
                                 {
                                    FILE *ptr = NULL;
                                    ptr = fopen("myfile2.txt","r");
                                    char str[34];
                                    fgets(str, 5, ptr);
                                    printf("The string is : %s\n", str);
                                    fclose(ptr);
                                    return 0;
                                 }