File is one type of storage non-volatile or permanent, as such data in the file can be written or read. In the C Programming language known as a file stream, stream is a collection of characters arranged in lines that move from one medium to another in a computer system. Manipulation of files can be done using stdio.h or fstream.h
File Manipulation Using stdio.h
In using the stdio.h header file of each file requires the declaration of a variable of type pointer to mark the files used in the operation of I/O. Following the declaration of the file pointer:
FILE *fp, *FP2
to open a file can use the function fopen. The function returns the file pointer value that is used or if an error occurs then the value NULL will be returned. The example below will open the file named program.c with mode "r" to read and in associated with the file pointer fp.
fp = fopen ("program.c","r");
There are several types of files used readout modes 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 exist)
- To write to a file in a specific format ==> int fprint(fp, "test \n"); if successful wil be refunded the amount of bytes written is returned EOF while if it fails (a constant that indicates the end of file)
- To read from a file in a specific field formats ==> int fscanf(fp,"test \n"); if successful will be refunded the amount of fields that should be read while the EOF is returned if it fails
- To write characters to a text file ==> int fputc (int c, FILE *fp);
- To read a text file per character ==> int fgetc(FILE *fp);
- To put an integer value to a file ==> putw int (int w, FILE *fp);
- To read integer value ==> int getw(FILE *fp);
- To write a string to a file without any NULL characters and newline ==> int fputs(const char *s, FILE *fp);
- To read a string of n characters of the file or see the characters '\n' ==> char *fgets(const char *s, int n, FILE *fp);
- To find out the end of a file stream ==> int feof(FILE *fp);
- To Close a file that is used in the program can be used to provide value fclose function returns the status of the program. Example : fclose(fp); //close the file pointer associated with fp
#include <stdio.h>
void main()
{
FILE *fp;
int x;
fp=fopen("test.txt", "r"); //open file test.txt
x=fgetc(fp);
while ( x != EOF )
{
putchar( x ); //display character in the file
x = fgetc ( fp ); //read character in the file
}
fclose ( fp ); //close file
}
Example 2: Programs for writing a total integer value to the user input file
#include <stdio.h>
#include <stdlib.h>
void main()
{
int n;
printf("Input : "); scanf("%d",&n);
FILE *fp;
if((fp=fopen("test.txt","w"))NULL) //check the file
{
printf("File Error");
exit(1);
}
for(int x=0; x<n; x++)
fprintf (fp, " %i\n", x);
fclose(fp);
}
0 comment:
Post a Comment