Presentation is loading. Please wait.

Presentation is loading. Please wait.

What you need for the 1st phase of project

Similar presentations


Presentation on theme: "What you need for the 1st phase of project"— Presentation transcript:

1 What you need for the 1st phase of project
File Handling in C What you need for the 1st phase of project

2 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. When a computer reads a file, it copies the file from the storage device to memory; when it writes to a file, it transfers data from memory to the storage device. C uses a structure called FILE (defined in stdio.h) to store the attributes of a file.

3 Steps in Processing a File
Create the stream via a pointer variable using the FILE structure: FILE *p; Open the file, associating the stream name with the file name. Read or write the data. Close the file.

4 The basic file operations are
fopen - open a file- specify how its opened (read/write) and type (binary/text) fclose - close an opened file fscanf- read from a file fprintf – write to a file fread - read from a file fwrite - write to a file fseek/fsetpos - move a file pointer to somewhere in a file. ftell/fgetpos - tell you where the file pointer is located. fgetc/fputc- read and write a char

5 File Open The file open function (fopen) serves two purposes:
It makes the connection between the physical file and the stream. It creates “a program file structure to store the information” C needs to process the file. Syntax: filepointer=fopen(“filename”, “mode”);

6 Mode Meaning fopen Returns if  FILE- Exists Not Exists r Reading NULL w Writing Over write on Existing Create New File a Append r+ Reading + Writing New data is written at the beginning overwriting existing data w+ a+ Reading + Appending New data is appended at the end of file

7 More on File Open Modes from Figure 7-4 in Forouzan & Gilberg, p. 401

8 More On fopen The file mode tells C how the program will use the file.
The filename indicates the system name and location for the file. We assign the return value of fopen to our pointer variable: spData = fopen(“MYFILE.TXT”, “w”); spData = fopen(“A:\\MYFILE.TXT”, “w”);

9 More On fopen from Figure 7-3 in Forouzan & Gilberg, p. 399

10 Closing a File When we finish with a mode, we need to close the file before ending the program or beginning another mode with that same file. To close a file, we use fclose and the pointer variable: fclose(spData);

11 Check the file exists or not!
#include <stdio.h> int main(void) { FILE *f; int x; f = fopen("test22.TXT", "r"); if(f!=NULL) { printf(“The file exists!\n"); fclose(f); } else { printf(“The file does not exist!"); return 0;

12 fscanf() Syntax: fscanf (fp,"string",identifiers); Example: FILE *fp;
Fp=fopen(“input.txt”,”r”); int i; fscanf (fp,“%d",&i);

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

14 fwrite() Writes an array of count elements, each one with a size of size bytes, from the block of memory pointed by ptr to the current position in the stream. The position indicator of the stream is advanced by the total number of bytes written. size_t fwrite ( const void * ptr, size_t size, size_t count, FILE * stream );

15 fwrite() example /* fwrite example : write buffer */
#include <stdio.h> int main () { FILE * pFile; char buffer[] = { 'x' , 'y' , 'z' }; pFile = fopen ("myfile.bin", "wb"); fwrite (buffer , sizeof(char), sizeof(buffer), pFile); fclose (pFile); return 0; }

16 fread() Reads an array of count elements, each one with a size of size bytes, from the stream and stores them in the block of memory specified by ptr. The position indicator of the stream is advanced by the total amount of bytes read. size_t fread ( void * ptr, size_t size, size_t count, FILE * stream );

17 #include <stdio.h>
int main () { FILE* file = fopen("test.txt", "rb"); int buffer[4]; if (file) { /* File was opened successfully. */ /* Attempt to read */ fread(buffer, 1, 4, file) ; printf("%s",buffer); fclose(file); }

18 fputc() int fputc(int char, FILE *stream)
The C library function int fputc(int char, FILE *stream) writes a character specified by the argument char to the specified stream and advances the position indicator for the stream. char -- This is the character to be written. This is passed as its int promotion. stream -- This is the pointer to a FILE object that identifies the stream where the character is to be written. If there are no errors, the same character that has been written is returned. If an error occurs, EOF is. int fputc(int char, FILE *stream)

19 #include <stdio.h>
int main () { FILE *fp; int ch; fp = fopen("test.txt", "w+"); for( ch = 33 ; ch <= 100; ch++ ) fputc(ch, fp); } fclose(fp); return(0);

20 EOF It is a macro definition of type int (by default equal to -1).
It is used as the value returned by several functions to indicate that the End-of-File has been reached or to signal some other failure conditions. It is also used as the value to represent an invalid character.

21 fgetc() Returns the character currently pointed by the internal file position indicator of the specified stream. The internal file position indicator is then advanced to the next character. If the stream is at the end-of-file when called, the function returns EOF and sets the end-of-file indicator for the stream (feof).

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

23 putc() write a single character to the output file, pointed to by fp. Example: FILE *fp; char ch; putc (ch,fp);

24 feof() Checks whether the end-of-File indicator associated with stream is set returning a value different from zero if it is. This indicator is generally set by a previous operation on the stream that attempted to read at or past the end-of-file.

25 feof example: byte counter
#include <stdio.h> int main () { FILE * pFile; int n = 0; pFile = fopen ("ss.txt","r"); while (fgetc(pFile) != EOF) { ++n; } if (feof(pFile)) { puts ("End-of-File reached."); printf ("Total number of bytes read: %d\n", n); fclose (pFile); return 0;

26 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 the fscanf function: FILE *fptr1; int istatus ; istatus = fscanf (fptr1, "%d", &var) ; if ( istatus == feof(fptr1) ) { printf ("End-of-file encountered.\n”) ; }

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

28 Example #include <stdio.h> #include<conio.h> void main() {
char ch; FILE *fp; fp=fopen("out.txt","r"); while(!feof(fp)) ch=getc(fp); printf("\n%c",ch); } getch();

29 fseek() 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. SEEK_SET Seeks from beginning of file SEEK_CUR Seeks from current position SEEK_END Seeks from end of file Example: #include <stdio.h> int main() {        FILE * f;        f = fopen("myfile.txt", "w");        fputs("Hello World", f);        fseek(f, 6, SEEK_SET); // SEEK_CUR, SEEK_END        fputs(" India", f);        fclose(f);        return 0; }

30 ftell() offset = ftell( file pointer ); "ftell" returns the current position for input or output on the file #include <stdio.h> int main(void) { FILE *stream; stream = fopen("MYFILE.TXT", "w"); fprintf(stream, "This is a test"); printf("The file pointer is at byte %ld\n", ftell(stream)); fclose(stream); return 0; }


Download ppt "What you need for the 1st phase of project"

Similar presentations


Ads by Google