Looking for a Tutor Near You?

Post Learning Requirement »
x

Choose Country Code

x

Direction

x

Ask a Question

x

x
x
x
Hire a Tutor

Files In C Programming

Loading...

Published in: C / C++ | Computer Science
7,856 Views

Detailed Notes Of Files In C Language

SR I / Hyderabad

year of teaching experience

Qualification:

Teaches: Advanced Excel, MS Office, B.Com Tuition, B.Sc Tuition, B.Tech Tuition, BCA Tuition, Computer Science, Electronics, IT, M.Tech Tuition, Mathematics, Polytechnic, Statistics, Chemical, Civil, Computer, Drawing, Electrical, Instrumentation, Mechanical, Production, C / C++, Java And J2EE, Python Programming, BCA Subjects, MCA Subjects, Java Script

Contact this Institute
  1. FILES in C Programming SR-IT @ Beeramguda Kamman The following topics are covered in this study material: Ph: 7396252455 1. 2. 3. 4. 5. 6. 7. Definition of files File using functions fopen and fclose functions character input /output functions String input and output functions Sequential vs random access files. Positioning the file pointers Why files are needed? When the program is terminated, the entire data is los C programming. If you want to keep large volume of data, it is time consuming to ente h ntire data. But, if file is Wbe accessed using e comman created, this informatio There are large numbers f fungtlons to handl il I/O in C anguage. In this study material, you will lea o handl andardl/ High level file I/O functions) in C. High level file I/O unctions can ategorized as: 1. Tex _fi 2. Binar 1 e File Operations fli 1. Creatin a 2. Opening an existing fl e 3. Reading from and writ n information to a file 4. Closing a file Working with file While working with file, you need to declare a pointer of type file. This declaration is needed for communication between file and program. FILE *ptr•, 1
  2. FILES in C Programming SR-IT @ Beeramguda Kamman fopen() and fclose() functions Opening a file Ph: 7396252455 Opening a file is performed using library function fopen(). The syntax for opening a file in standard I/O is: , "mode For Example : SYNTAX:- fopen("E "w"); E:\\cprogram\program.txt is the location to creat file. "w" represents the mode for writing. Here, the program.txt file is opened for writing;mode. Opening Modes in Standard I/O File Mode a eaning of Mode During Inexistence of file If the file does not o en() returns NULL. exist, Open pen Open o re ding or WE ting. for p end. If the file exists, its contents are overwritten. If the file does not exist, it will be created. If the file does not exists, it i.e, Data s a ed to endo i Open for both reading and writing. will be created. If the file does not fopen() returns NULL. exist, Open for both If the file exists, its contents are overwritten. If the file does 2
  3. FILES in C Programming SR-IT @ Beeramguda Kamman Opening Modes in Standard I/O Ph: 7396252455 File Mode Closing a File eaning of Mode reading and writing. Open for both During Inexistence of file not exist, it will be created. If th 11 does not exists, e reated. it reading appending. and The file should be closed after reading/writing of a fi losing a file is performed using library function fclose(). SYNTAX:- fclose(ptr); //pt 11 pointer assocl ted with i e o be closed. The Functions fprintf and fscanf ) functions. Important •s ha the function prmtf and scanf() are the file version of printf() and fscanf() h n y differen Ile using pont and fscanf() is that, the first argument is a pointe to the structure FI Charac erinputMååfrRfunctions ,String input and output functions Examples:- Writing to a file #include int main() int n; FILE *fptr; 3
  4. FILES in C Programming SR-IT @ Beeramguda Kamman printf("Error!"); exit(l); printf("Enter n: "); scanf("%d",&n); fprintf(fptr, " ,n); fclose(fptr); return 0; Ph: 7396252455 This program takes the number from user and stores i 11 . After you compile and run this program, you can see a text file program.txt cre te in C drive of your computer. When you open that file, you can see the integer y u entered. Similarly, fscanf() can be used to read data fro fil Reading from file #include int main() int n; FILE *fptr•, if ((fptr=fopen(" rogram, St", ){ printf("Erro ppening fil P ogram e It if file pointer returns NULL. */ exit(l fscanf fpt od",&n printi v' ue ofn=%d fclose fptr); ret rn mppgram bov to wr1W n file successfully, you can get the integer back If you hav entered in that program usin th s program. Other functions like fgetchar putc() etc. can be used in similar way. Description The C library function int fputc(int char, FILE *stream) writes a character (an unsigned char) specified by the argument char to the specified stream and advances the position indicator for the stream. Declaration Following is the declaration for fputc() function. 4
  5. FILES in C Programming SR-IT @ Beeramguda Kamman SYNTAX:- int fputc(int char, FLE *stream) Parameters Ph: 7396252455 • char -- This is 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. Return Value If there are no errors, the same character that has been written is returned. If an error occurs, EOF is retumed and the error indicator is set. Example The following example shows the usage of fputc() function. #include int main ( ) FILE *fp; int ch; fp =fopen("file.txt", "w+"); for( ch = 33 ; ch
  6. FILES in C Programming SR-IT @ Beeramguda Kamman int main ( ) FILE *fp; int c; fp =fopen("file.txt , "r"); while(l) c =fgetcffp); feofffp) ) break ; printf("%c' , c); fclose(fp); return(O); Binary Files Depending upon the wa 1 e pened for pro e sing, 1 and binary file. Ph: 7396252455 •s classified into text file If a large amount o umericald t t to be to ed, text mode will be insufficient. In such case binary file is u e Aex files with few differences in opening modes, Working of binary fi e imil r reading fr 1 and wrltln t Opening modes of binary files Opening o eyyynary .11gyare r r , wb, wb+,ab and ab+. The only difference between opening modes of tex and binary files is that, b is appended to indicate that, it is binary file. Reading and writing of a bmary file. Functions fread() and write() are used for reading from and writing to a file on the disk respectively in case of binary files. Function fwrite() takes four arguments, address of data to be written in disk, size of data to be written in disk, number of such type of data and pointer to the file where you want to write. Syntax:- fwrite(address_data,size_data,num ; 6
  7. FILES in C Programming SR-IT @ Beeramguda Kamman Ph: 7396252455 Function fread() also take 4 arguments similar to fwrite() function as above. Sequential and Random Access File Handlinq in C Sequential access 1 2 3 4 5 6 7 8 Random access 1 3 7 2 8 6 4 5 In computer programming, the two main types of file handling are: Sequential; Random access. Sequential files are generally used in cases where the program processes the data in a sequential fashion — i.e. counting words in a text file — although in some cases, random access can be feigned by moving backwards and forwards over a sequential file. True random access file handling, however, only accesses the file at the point at which the data should be read or written, rather than having to process it sequentially. A hybrid approach is also possible whereby a part of the file is used for sequential access to locate something in the 7
  8. FILES in C Programming SR-IT @ Beeramguda Kamman Ph: 7396252455 random access portion of the file, in much the same way that a File Allocation Table (FAT) works. The three main functions are: rewind() — return the file pointer to the beginning; fseek() — position the file pointer; ftell() — return the current offset of the file pointer. Each of these functions operates on the C file pointer, which is just the offset from the start of the file, and can be positioned at will. All read/write operations take place at the current position of the file pointer. The rewind() Function The rewind() function can be used in sequential or random access C file programming, and simply tells the file system to position the file pointer at the start of the file. Any error flags will also be cleared, and no value is returned. While useful, the companion function, fseek(), can also be used to reposition the file pointer at will, including the same behavior as rewind(). Using fseek() and ftell() to Process Files* Positioning the file pointers The fseek() function is most useful in random access files where either the record (or block) size is known, or there is an allocation system that denotes the start and end positions of records in an index portion of the file. The fseek() function takes three parameters: FILE * f- the file pointer; long offset — the position offset; int origin — the point from which the offset is applied. 8
  9. FILES in C Programming SR-IT @ Beeramguda Kamman The origin parameter can be one of three values: SEEK SET - from the start; SEEK_CUR — from the current position; SEEK END - from the end of the file. So, the equivalent of rewind() would be: fseek( f, O, SEEK_SET)•, Ph: 7396252455 By a similar token, if the programmer wanted to append a record to the end of the file, the pointer could be repositioned thus: fseek( f, O, SEEK_END); Since fseek() returns an error code (0 for no error) the stdio library also provides a function that can be called to find out the current offset within the file: long offset = ftell( FILE * f) This enables the programmer to create a simple file marker (before updating a record for example), by storing the file position in a variable, and then supplying it to a call to fseek: long file _ marker = ftell(f); // ... file processing functions fseek( f, file_marker, SEEK_SET); 9
  10. FILES in C Programming SR-IT @ Beeramguda Kamman Ph: 7396252455 Of course, if the programmer knows the size of each record or block, arithmetic can be used. For example, to rewind to the start of the current record, a function call such as the following would suffice: fseek( f, O - record_size, SEEK_CURR)•, With these three functions, the C programmer can manipulate both sequential and random access files, but should always remember that positioning the file pointer is absolute. In other words, if fseek is used to position the pointer in a read/write file, then writing will overwrite existing data, permanently. ERROR HANDLING IN FILES:- In this C language study material I am going to look at error handling. Although C programming does not provide direct support for error handling (also called exception handling), there are ways to do error handling. Of course the programmer needs to prevent errors during coding and should always test the return values of functions called by the program. A lot of C function calls return a -1 or NULL in case of an error, so quick test on these return values are easily done with for instance an 'if statement'. For instance if a program successful ends the retum value of the program is zero. If the program ends with an error usually a number larger than zero is returned (for example 1). So, the one thing you need to remember is that you (the programmer) are responsible for error handling. You're the person that needs to make sure that a program will gracefully terminate and not just CRASH unexpectedly! It is you that need to take appropriate action depending on the return values of function calls. Global Variable errno The global variable errno is used by C functions and this integer is set if there is an error during the function call. To make use of errno you need to include errno.h and you need to call 'extern int errno;' Let us take a look at an example: 10
  11. FILES in C Programming SR-IT @ Beeramguda Kamman #include #include extern int errno; int main ( ) { FILE *fp; fp =fopen ("filedoesnotexist.txt", "rb if(fp NULL) { fprintf(stderr, "Value oferrno: %d\n ' , errno); } else { fclose (fp); return 0; The output of the program will be something like: Value of errno is: 2 Ph: 7396252455 As you can see we include the stdio.h and errno.h header files. Then 'extern int errno' is called, so we now have access to the integer errno. To generate an error we open a file that doesn't exist. If the file pointer (fp) equals NULL then we print the value of errno (in this case errno will be 2). If we get a file pointer (in case the file exists) we close the file. The functions strerror() and perror() In the previous example the errno had a value of 2. But what is the meaning of the value of 2? How does the user know what this error is? Of course a good practice is to make some documentation where you describe each error number and what the user should do. But it is also a good practice to give a good descriptive error message when an error occurs in the program. The C programming language has two functions that can be used to display a text message that is associated with errno. The functions are strerror() and perror(). 11
  12. FILES in C Programming SR-IT @ Beeramguda Kamman Ph: 7396252455 The function strerror() returns a pointer to the textual message of the current errno value. The function perror() displays a string you pass to it, followed by a colon and the textual message of the current errno value. -------------------------This ends the basic File concepts--- Basic C- Files Examples:- 1. Write a C program to read name and marks of n number of students from user and store them in a file. #include #include int main(){ char name[50]; int marks,i,n; clrscr(); printf("Enter number of students: ; scanf("%d" ,&n); FILE *fptr; " C:\ \ student .txt" ,"w ")); pri ntf(" Er ror !") ; exit(l); printf("For student%d\ nEnter name scanf("%s" ,name) ; printf(" Enter marks: ; scanf("%d" ; fpri ntf(fptr ,"\ n Name: %s \ nMarks=%d \ n" ,name,marks) ; fclose(fptr) ; getch(); return 0; 12
  13. FILES in C Programming SR-IT @ Beeramguda Kamman Ph: 7396252455 from user and store them in a file. If the file previously exits, add the 2. 3. Write a C program to read name and marks of n number of students information of n students. #include #include int main(){ char name[50]; int marks,i,n; clrscr(); printf(" Enter number of students scanf(" 0/0d" ,&n); FILE * if(fptr==NULL){ printf(" Error!"); exit(l); printf(" For student%d\nEnter name: scanf (" O/os" ,nam e) ; printf(" Enter marks: 'I); scanf(" %d" ,&marks); fprintf(fptr,"\ nName: %s \ nM arks=%d \ n" ,name,marks); fclose(fptr); getch ( ) ; return 0; Write a C program to write all the members of an array of strcures to a file using fwrite(). Read the array from the file and display on the screen. #include #include struct s 13
  14. FILES in C Programming SR-IT @ Beeramguda Kamman char name[50] ; int height; int main(){ struct s FILE *fptr•, int i; clrscr(); fptr=fopen("file.txt","wb ) for(i=0;i