Files In C Language
File : File is a collection of data or information which is used to store the data permanently
Types of files:
1.Text Files
2.Document Files
3.Audio Files
4.Video Files
5.PDF Files ...
File Operations
1.Open or create a file
2.Write the data into the file
3.Read the data from the file
4.close a file
Open file
If you are going to handle binary files, then you will use following access modes instead of the above mentioned ones −
Writing a File:
Types of files:
1.Text Files
2.Document Files
3.Audio Files
4.Video Files
5.PDF Files ...
File Operations
1.Open or create a file
2.Write the data into the file
3.Read the data from the file
4.close a file
Open file
FILE *fopen( const char * filename, const char * mode );Here, filename is a string literal, which you will use to name your file, and access mode can have one of the following values −
| Sno | Mode | Description |
| 1 | r | Opens an existing text file for reading purpose. |
| 2 | w | Opens a text file for writing. If it does not exist, then a new file is created. Here your program will start writing content from the beginning of the file. |
| 3 | a | Opens a text file for writing in appending mode. If it does not exist, then a new file is created. Here your program will start appending content in the existing file content. |
| 4 | r+ | Opens a text file for both reading and writing. |
| 5 | 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. |
| 6 | 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 be appended. |
If you are going to handle binary files, then you will use following access modes instead of the above mentioned ones −
"rb", "wb", "ab", "rb+", "r+b", "wb+", "w+b", "ab+", "a+b"Closing File:
int fclose( FILE *fp ); Close a file using fclose( ) function
Writing a File:
fprintf(file,"Data")
fputs("Data",File)Program:#include <stdio.h>
#include <conio.h>
void main() {
FILE *fp;
fp = fopen("test.txt", "w+");
fprintf(fp, "This is testing File\n");
fputs("This is testing File\n", fp);
fclose(fp);
printf("Success");
getch();
}
Reading a Filefscanf(File,"type of data",variable);
fgets(variable,size, FILE)Program
#include <stdio.h>
#include <conio.h>
void main() {
FILE *fp;
char x[255];
fp = fopen("test.txt", "r");
fscanf(fp, "%s", x);
printf("1 : %s\n", x );
fgets(x, 255, (FILE*)fp);
printf("2: %s\n", x );
fclose(fp);
printf("Success");
getch();
}

No comments:
Post a Comment