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 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
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 <stdio.h>
int main()
{
FILE *fp;
fp = fopen(“test.txt”, “r”);
fclose(fp);
return 0;
}
Example
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *input_fp;
input_fp = fopen( "text.txt" , "r" );
if (input_fp == NULL )
{
exit(1);
}
fclose(input_fp);
return 0;
}
Functions
Prototype
Prototype
int *fgetc(FILE *fp);
int fputc(int c, FILE *fp);
Example
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *input_fp;
char ch;
input_fp = fopen( "text.txt" , "r" );
if (input_fp == NULL )
{
exit(1);
}
while ((ch = fgetc(input_fp)) != EOF )
{
fputc(ch, stdout );
}
fclose(input_fp);
return 0;
}
Prototype
int fprintf(char *string, char *format, ...);
Example
#include <stdio.h>
#include <stdlib.h>
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:
Post a Comment