Files
- A collection of related data treated as a unit
- Files are store in secondary devices
- Read files - the data move from the external device to RAM
- Write files - the data move from RAM to external devices
- The data movement uses a special work area called buffer that act as a temporary storage area
Files and Streams
- A stream is a sequence of elements in time
- A file is define by using a standard FILE type
- The format for the file type is shown below
- FILE *filename
- The asterisk is an address that pointed by the filename pointer
Standard Library Input/Output Functions
- The open/close functions, fopen and fclose, are used to open and close the association between external files and internal streams
- A file in C can be any of three basic modes:
- reading, r
- writing, w
- appending, a
- Standard format
- fopen ("filename", "mode");
- Example:
File *Infile;
Infile = fopen ("Data.dat", "w");
- When a file is opened in reading mode, the file marker is positioned at the beginning of the existing file
- When a file is opened in writing mode, the file marker is positioned at the beginning of the newly created empty file
- When a file is opened for appending, the file marker is positioned at the end of existing file, before the end-of-file marker
- fclose is used to closed and opened file
- fclose(Infile);
Formatting Input/Output Functions
- Formatted input/output functions allow read data from and write data to file character by character while formatting to the desired data type
- scanf and fscanf are used for reading
File *fpInput;
fpInput = fopen("data.dat", "r");
fscanf(fpInput, "%d-%d-%d", &day, &month, &year);
- printf and fprintf are used for writing
File *fpOutput;
fpOutput = fopen("data.dat", "w");
fprintf(fpOutput, "The date is %d-%d-%d", day, month, year);
- Example
#include
void main () {
int num, sum = 0;
FILE *inptr, *outptr;
if ((inptr = fopen(“infile.txt”, “r”)) != NULL) {
while(fscanf(inptr, “%d”, &num) != EOF)
sum += num;
fclose(inptr);
if ((outptr = fopen(“outfile.txt”, “w”)) != NULL) {
fprintf(outptr,“The sum of the numbers is %d\n”,sum);
fclose(outptr);
}
}
return ;
Character Input and Output
- Character input and output are used to read or write files character by character
- fgetc, getc, and getchar can be used for reading
- Example:
- charatcter = getchar( ) //Get character from keyboard
- character = getc(filepointer) //Get character from file
- character = fgetc(file pointer) //Get character from file
- fputc, putc and putchar can be used for writing
- Example
- putchar(character)
- fputc (character, filepointer)
- putc (character, filepointer
No comments:
Post a Comment