File Handling in C

25
CSCI N305: CSCI N305: C Programming C Programming Copyright Copyright ©2006 ©2006 Department of Computer & Information Science Department of Computer & Information Science File Handling in C File Handling in C

description

File Handling in C. What is a File?. A file is a collection of related data that a computers treats as a single unit. Computers store files to secondary storage so that the contents of files remain intact when a computer shuts down. - PowerPoint PPT Presentation

Transcript of File Handling in C

Page 1: File Handling in C

CSCI N305:CSCI N305: C ProgrammingC Programming

Copyright Copyright ©2006 ©2006 Department of Computer & Information ScienceDepartment of Computer & Information Science

File Handling in CFile Handling in C

Page 2: File Handling in C

N305: C ProgrammingN305: C ProgrammingCopyright Copyright ©2006 ©2006 Department of Computer & Information ScienceDepartment of Computer & Information Science

What is a File?What is a File?

• A A filefile is a collection of related data that a is a collection of related data that a computers treats as a single unit.computers treats as a single unit.

• Computers store files to secondary storage so Computers store files to secondary storage so that the contents of files remain intact when a that the contents of files remain intact when a computer shuts down.computer shuts down.

• When a computer reads a file, it copies the file When a computer reads a file, it copies the file from the storage device to memory; when it from the storage device to memory; when it writes to a file, it transfers data from memory to writes to a file, it transfers data from memory to the storage device.the storage device.

• C uses a structure called C uses a structure called FILEFILE (defined in (defined in stdio.hstdio.h) to store the attributes of a file.) to store the attributes of a file.

Page 3: File Handling in C

N305: C ProgrammingN305: C ProgrammingCopyright Copyright ©2006 ©2006 Department of Computer & Information ScienceDepartment of Computer & Information Science

Steps in Processing a FileSteps in Processing a File

1.1. Create the stream via a pointer Create the stream via a pointer variable using the variable using the FILEFILE structure: structure:FILE *p;FILE *p;

2.2. Open the file, associating the stream Open the file, associating the stream name with the file name.name with the file name.

3.3. Read or write the data.Read or write the data.4.4. Close the file.Close the file.

Page 4: File Handling in C

N305: C ProgrammingN305: C ProgrammingCopyright Copyright ©2006 ©2006 Department of Computer & Information ScienceDepartment of Computer & Information Science

The basic file operations areThe basic file operations are

• fopen - open a file- specify how its opened fopen - open a file- specify how its opened (read/write) and type (binary/text) (read/write) and type (binary/text)

• fclose - close an opened file fclose - close an opened file • fread - read from a file fread - read from a file • fwrite - write to a file fwrite - write to a file • fseek/fsetpos - move a file pointer to somewhere fseek/fsetpos - move a file pointer to somewhere

in a file. in a file. • ftell/fgetpos - tell you where the file pointer is ftell/fgetpos - tell you where the file pointer is

located. located.

Page 5: File Handling in C

N305: C ProgrammingN305: C ProgrammingCopyright Copyright ©2006 ©2006 Department of Computer & Information ScienceDepartment of Computer & Information Science

File Open ModesFile Open Modes

from Table 7-1 in Forouzan & Gilberg, p. 400

Page 6: File Handling in C

N305: C ProgrammingN305: C ProgrammingCopyright Copyright ©2006 ©2006 Department of Computer & Information ScienceDepartment of Computer & Information Science

More on File Open ModesMore on File Open Modes

from Figure 7-4 in Forouzan & Gilberg, p. 401

Page 7: File Handling in C

N305: C ProgrammingN305: C ProgrammingCopyright Copyright ©2006 ©2006 Department of Computer & Information ScienceDepartment of Computer & Information Science

Additionally,Additionally,

• r+ - open for reading and writing, start r+ - open for reading and writing, start at beginningat beginning

• w+ - open for reading and writing w+ - open for reading and writing (overwrite file)(overwrite file)

• a+ - open for reading and writing a+ - open for reading and writing (append if file exists) (append if file exists)

Page 8: File Handling in C

N305: C ProgrammingN305: C ProgrammingCopyright Copyright ©2006 ©2006 Department of Computer & Information ScienceDepartment of Computer & Information Science

File OpenFile Open

• The file open function (The file open function (fopenfopen) serves ) serves two purposes:two purposes:– It makes the connection between the physical It makes the connection between the physical

file and the stream.file and the stream.– It creates “a program file structure to store the It creates “a program file structure to store the

information” C needs to process the file.information” C needs to process the file.

• Syntax:Syntax:filepointer=filepointer=fopen(“filename”, “mode”);fopen(“filename”, “mode”);

Page 9: File Handling in C

N305: C ProgrammingN305: C ProgrammingCopyright Copyright ©2006 ©2006 Department of Computer & Information ScienceDepartment of Computer & Information Science

More On More On fopenfopen

• The file mode tells C how the program will The file mode tells C how the program will use the file.use the file.

• The filename indicates the system name The filename indicates the system name and location for the file.and location for the file.

• We assign the return value of We assign the return value of fopenfopen to our to our pointer variable:pointer variable:spData = fopen(“MYFILE.TXT”, “w”);spData = fopen(“MYFILE.TXT”, “w”);

spData = fopen(“A:\\MYFILE.TXT”, “w”);spData = fopen(“A:\\MYFILE.TXT”, “w”);

Page 10: File Handling in C

N305: C ProgrammingN305: C ProgrammingCopyright Copyright ©2006 ©2006 Department of Computer & Information ScienceDepartment of Computer & Information Science

More On More On fopenfopen

from Figure 7-3 in Forouzan & Gilberg, p. 399

Page 11: File Handling in C

N305: C ProgrammingN305: C ProgrammingCopyright Copyright ©2006 ©2006 Department of Computer & Information ScienceDepartment of Computer & Information Science

Closing a FileClosing a File

• When we finish with a mode, we need When we finish with a mode, we need to close the file before ending the to close the file before ending the program or beginning another mode program or beginning another mode with that same file.with that same file.

• To close a file, we use To close a file, we use fclosefclose and and the pointer variable:the pointer variable:fclose(spData);fclose(spData);

Page 12: File Handling in C

N305: C ProgrammingN305: C ProgrammingCopyright Copyright ©2006 ©2006 Department of Computer & Information ScienceDepartment of Computer & Information Science

fprintf()fprintf()

Syntax:Syntax:fprintf (fp,"string",variables); fprintf (fp,"string",variables);

Example:Example:int i = 12; int i = 12; float x = 2.356; float x = 2.356; char ch = 's'; char ch = 's'; FILE *fp;FILE *fp;fp=fopen(“out.txt”,”w”);fp=fopen(“out.txt”,”w”);fprintf (fp, "%d %f %c", i, x, fprintf (fp, "%d %f %c", i, x, ch); ch);

Page 13: File Handling in C

N305: C ProgrammingN305: C ProgrammingCopyright Copyright ©2006 ©2006 Department of Computer & Information ScienceDepartment of Computer & Information Science

fscanf()fscanf()

Syntax:Syntax:

fscanf (fp,"string",identifiers); fscanf (fp,"string",identifiers);

Example:Example:FILE *fp;FILE *fp;

Fp=fopen(“input.txt”,”r”);Fp=fopen(“input.txt”,”r”);

int i; int i;

fscanf (fp,“%d",i); fscanf (fp,“%d",i);

Page 14: File Handling in C

N305: C ProgrammingN305: C ProgrammingCopyright Copyright ©2006 ©2006 Department of Computer & Information ScienceDepartment of Computer & Information Science

getc()getc()

Syntax:Syntax:identifier = getc (file pointer);identifier = getc (file pointer);Example:Example:FILE *fp; FILE *fp; fp=fopen(“input.txt”,”r”);fp=fopen(“input.txt”,”r”);char ch; char ch; ch = getc (fp); ch = getc (fp);

Page 15: File Handling in C

N305: C ProgrammingN305: C ProgrammingCopyright Copyright ©2006 ©2006 Department of Computer & Information ScienceDepartment of Computer & Information Science

putc()putc()write a single character to the output write a single character to the output

file, pointed to by fp. file, pointed to by fp.

Example:Example:

FILE *fp; FILE *fp;

char ch; char ch;

putc (ch,fp); putc (ch,fp);

Page 16: File Handling in C

N305: C ProgrammingN305: C ProgrammingCopyright Copyright ©2006 ©2006 Department of Computer & Information ScienceDepartment of Computer & Information Science

End of FileEnd of File

• There are a number of ways to test for the end-of-file There are a number of ways to test for the end-of-file condition. Another way is to use the value returned by condition. Another way is to use the value returned by the the fscanffscanf function: function:

FILE *fptr1;FILE *fptr1;int istatus ;int istatus ;istatus = fscanf (fptr1, "%d", &var) ;istatus = fscanf (fptr1, "%d", &var) ;if ( istatus == feof(fptr1) )if ( istatus == feof(fptr1) ){{

printf ("End-of-file encountered.\n”) ;printf ("End-of-file encountered.\n”) ;}}

Page 17: File Handling in C

N305: C ProgrammingN305: C ProgrammingCopyright Copyright ©2006 ©2006 Department of Computer & Information ScienceDepartment of Computer & Information Science

Reading and Writing FilesReading and Writing Files#include <stdio.h>#include <stdio.h>int main ( )int main ( ){{ FILE *outfile, *infile ;FILE *outfile, *infile ; int b = 5, f ;int b = 5, f ; float a = 13.72, c = 6.68, e, g ;float a = 13.72, c = 6.68, e, g ; outfile = fopen ("testdata", "w") ;outfile = fopen ("testdata", "w") ; fprintf (outfile, “ %f %d %f ", a, b, c) ;fprintf (outfile, “ %f %d %f ", a, b, c) ; fclose (outfile) ;fclose (outfile) ; infile = fopen ("testdata", "r") ;infile = fopen ("testdata", "r") ; fscanf (infile,"%f %d %f", &e, &f, &g) ;fscanf (infile,"%f %d %f", &e, &f, &g) ; printf (“ %f %d %f \n ", a, b, c) ;printf (“ %f %d %f \n ", a, b, c) ; printf (“ %f %d %f \n ", e, f, g) ;printf (“ %f %d %f \n ", e, f, g) ;}}

Page 18: File Handling in C

N305: C ProgrammingN305: C ProgrammingCopyright Copyright ©2006 ©2006 Department of Computer & Information ScienceDepartment of Computer & Information Science

ExampleExample#include <stdio.h>#include <stdio.h>#include<conio.h>#include<conio.h>void main()void main(){{

char ch;char ch;FILE *fp;FILE *fp;fp=fopen("out.txt","r");fp=fopen("out.txt","r");while(!feof(fp))while(!feof(fp))

{{ch=getc(fp);ch=getc(fp);printf("\n%c",ch);printf("\n%c",ch);

}}getch();getch();

}}

Page 19: File Handling in C

N305: C ProgrammingN305: C ProgrammingCopyright Copyright ©2006 ©2006 Department of Computer & Information ScienceDepartment of Computer & Information Science

freadfread () ()

Declaration:Declaration: size_t fread(void *ptr, size_t size, size_t n, FILE *stream);size_t fread(void *ptr, size_t size, size_t n, FILE *stream);

Remarks:Remarks:fread reads a specified number of equal-sizedfread reads a specified number of equal-sizeddata items from an input stream into a block.data items from an input stream into a block.

ptr = Points to a block into which data is readptr = Points to a block into which data is read size = Length of each item read, in bytessize = Length of each item read, in bytes n = Number of items readn = Number of items read stream = file pointerstream = file pointer

Page 20: File Handling in C

N305: C ProgrammingN305: C ProgrammingCopyright Copyright ©2006 ©2006 Department of Computer & Information ScienceDepartment of Computer & Information Science

ExampleExample

Example:Example:#include <stdio.h>   #include <stdio.h>   int main() int main() { {

FILE *f;  FILE *f;   char buffer[11];char buffer[11]; if (f = fopen("fred.txt", “r”)) if (f = fopen("fred.txt", “r”))

{ { fread(buffer, 1, 10, f); fread(buffer, 1, 10, f); buffer[10] = 0; buffer[10] = 0; fclose(f); fclose(f); printf("first 10 characters of the file:\n%s\n", buffer);printf("first 10 characters of the file:\n%s\n", buffer); }  }  

return 0; return 0; }}

Page 21: File Handling in C

N305: C ProgrammingN305: C ProgrammingCopyright Copyright ©2006 ©2006 Department of Computer & Information ScienceDepartment of Computer & Information Science

fwrite()fwrite()

Declaration:Declaration: size_t fwrite(const void *ptr, size_t size, size_t n, FILE*stream);size_t fwrite(const void *ptr, size_t size, size_t n, FILE*stream);

Remarks:Remarks:fwrite appends a specified number of equal-sized data items to an fwrite appends a specified number of equal-sized data items to an

output file.output file.

ptr = Pointer to any object; the data written begins at ptrptr = Pointer to any object; the data written begins at ptr size = Length of each item of datasize = Length of each item of data n =Number of data items to be appendedn =Number of data items to be appended stream = file pointerstream = file pointer

Page 22: File Handling in C

N305: C ProgrammingN305: C ProgrammingCopyright Copyright ©2006 ©2006 Department of Computer & Information ScienceDepartment of Computer & Information Science

ExampleExample

Example:Example:#include <stdio.h>#include <stdio.h>int main()int main(){{

char a[10]={'1','2','3','4','5','6','7','8','9','a'};char a[10]={'1','2','3','4','5','6','7','8','9','a'};FILE *fs;FILE *fs;fs=fopen("Project.txt","w");fs=fopen("Project.txt","w");fwrite(a,1,10,fs);fwrite(a,1,10,fs);fclose(fs);fclose(fs);return 0;return 0;

} }

Page 23: File Handling in C

N305: C ProgrammingN305: C ProgrammingCopyright Copyright ©2006 ©2006 Department of Computer & Information ScienceDepartment of Computer & Information Science

fseek()fseek()This function sets the file position indicator for the stream pointed to by stream This function sets the file position indicator for the stream pointed to by stream or you can say it seeks a specified place within a file and modify it.or you can say it seeks a specified place within a file and modify it.

SEEK_SET SEEK_SET Seeks from beginning of file Seeks from beginning of file SEEK_CUR SEEK_CUR Seeks from current position Seeks from current position SEEK_END SEEK_END Seeks from end of file Seeks from end of file

Example:Example:#include#include <stdio.h> <stdio.h>intint mainmain()() {{

       FILE * f;       FILE * f;       f = fopen("myfile.txt", "w");       f = fopen("myfile.txt", "w");       fputs("Hello World", f);       fputs("Hello World", f);       fseek(f, 6, SEEK_SET); SEEK_CUR, SEEK_END       fseek(f, 6, SEEK_SET); SEEK_CUR, SEEK_END       fputs(" India", f);       fputs(" India", f);       fclose(f);       fclose(f);              returnreturn 0; 0;} }

Page 24: File Handling in C

N305: C ProgrammingN305: C ProgrammingCopyright Copyright ©2006 ©2006 Department of Computer & Information ScienceDepartment of Computer & Information Science

ftell()ftell() offset = ftell( file pointer ); offset = ftell( file pointer );

"ftell" returns the current position for input or output on the file "ftell" returns the current position for input or output on the file #include <stdio.h>#include <stdio.h>

int main(void)int main(void){{ FILE *stream;FILE *stream; stream = fopen("MYFILE.TXT", "w");stream = fopen("MYFILE.TXT", "w"); fprintf(stream, "This is a test");fprintf(stream, "This is a test"); printf("The file pointer is at byte %ld\n", ftell(stream));printf("The file pointer is at byte %ld\n", ftell(stream)); fclose(stream);fclose(stream); return 0;return 0;}}

Page 25: File Handling in C

N305: C ProgrammingN305: C ProgrammingCopyright Copyright ©2006 ©2006 Department of Computer & Information ScienceDepartment of Computer & Information Science

THANK YOUTHANK YOU