Header Ads

3.8 - File Input / Output


 File Input / Output
  • Sequence of bytes 
  • Could be regular or binary file 
  • Why?
    • Persistent storage 
    • Theoretically unlimited size 
    • Flexibility of storing any type data
Redirection
  • General way for feeding and getting the output is using standard input (keyboard) and output (screen) 
  • By using redirection we can achieve it with files i.e ./a.out < input_file > output_file 
  • The above line feed the input from input_file and output to output_file 
  • The above might look useful, but its the part of the OS and the C doesn't work this way 
  • C has a general mechanism for reading and writing files, which is more flexible than redirection 
  • C abstracts all file operations into operations on streams of bytes, which may be "input streams" or "output streams" 
  • No direct support for random-access data files 
  • To read from a record in the middle of a file, the programmer must create a stream, seek to the middle of the file, and then read bytes in sequence from the stream 
  • Let's discuss some commonly used file I/O functions

File Pointer

  • stdio.h is used for file I/O library functions
  • The data type for file operation generally is
Type
FILE *fp; 
  • FILE pointer, which will let the program keep track of the file being accessed
  • Operations on the files can be
– Open
– File operations
– Close
 
Functions
Prototype
FILE *fopen(const char *filename, const char *mode);
int fclose(FILE *filename);
Where mode are: r - open for reading w - open for writing (file need not exist) a - open for appending (file need not exist) r+ - open for reading and writing, start at beginning w+ - open for reading and writing (overwrite file) a+ - open for reading and writing (append if file exists)  
Example
#include 
int main()
{
    FILE *fp;
    fp = fopen(“test.txt”, “r”);
    fclose(fp);
return 0;
} 
Example
#include 
#include 
int main()
{
    FILE *input_fp;
    input_fp = fopen( "text.txt" , "r" );
    if (input_fp == NULL )
    {
    exit(1);
    }
    fclose(input_fp);
return 0;
}

Functions  
Prototype
int *fgetc(FILE *fp);
int fputc(int c, FILE *fp);
Prototype
int fprintf(char *string, char *format, ...);
Example:
#include 
#include 
int main()
{
    FILE *input_fp;
    input_fp = fopen( "text.txt" , "r" );
    if (input_fp == NULL )
    {
        fprintf(stderr , "Can't open input file text.txt!\n" );
        exit(1);
    }
        fclose(input_fp);
    return 0;
}

No comments