0% found this document useful (0 votes)
6 views

files in c

This document provides an overview of file handling in C, including the concepts of text and binary files, and the standard library functions used for file operations. It explains how to create, open, read, write, and close files, as well as the different modes for file access. Additionally, it covers the use of functions like fseek for random access to data within files.

Uploaded by

sayakalu840
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
6 views

files in c

This document provides an overview of file handling in C, including the concepts of text and binary files, and the standard library functions used for file operations. It explains how to create, open, read, write, and close files, as well as the different modes for file access. Additionally, it covers the use of functions like fseek for random access to data within files.

Uploaded by

sayakalu840
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 10
After reading this chapter, the readers will be able to “= Analyze the concept of streams used in the C file system. Discuss a text and binary file. Process text files as well as binary files using standard library functions. aay Explain the sequential and random access of data stored in a disk file using proper standard library functions. In programming, we may require some specific input data to be generated several times. Sometimes, it is not enough to only display the data on the console. The data to be displayed may be very large, and only a limited amount of data ean be displayed on the console. Since the memory is volatile, it is impossible to recover the programmatically generated data repeatedly. However, if we need to do so, we may store it in the local file system, which is volatile and can not be accessed every time. Here comes the need for file handling in C. File handling refers to the method of storing data in the C program in the form of an output or input that might have been generated while running @ C program in a data file, ie, a binary file or a text file for future analysis and reference in that same program. ay GS {i2i Coneept of File "| ‘The file is a collection of bytes stored on secondary storage devices like disk. There at two kinds of files in a system. They are, 566 Pag Fe a ding jg Hane fie 667 ext files (ASCID © inary files. & ost files contain ASCII codes of digits, alphabets, and symbols ‘The binary file contains a collection of bytes (0's and 1's), Binary files are compiled * ‘ersions of text files, why are files needed? : When a program is terminated, the entire data is lost. Storing in a file will preserve our data even if the program terminates ¢ Ifwe have to enter a large number of data, it will take much time to enter them all However, if we have a file containing all the data, we can easily access the file's contents using a few commands in C. We can easily move our data from one computer to another without any changes. 441. Text Files ext files are the normal .txt files which we can easily create using Notepad or simple text editors. When we open those files, we will see all the contents within the file as plain test. We can easily edit or delete the contents. They take minimum effort to maintain, are tesily readable, provide the least security, and does not take up bigger storage space. 44.12 Binary Files Binary files are mostly the bin files in our computer. Instead of storing data in plain text, they store it in binary form (0's and 1’s). They can hold more data, are not readable casily, and provide better security than text files. U2 Basics of File Handling in © | So far, the operations of the C program hae been executed on a prompt/terminal and are aut stored anywhere, However, in the software industry, most programs are designed to store the information generated by the program. One such way is to store the fetched information in a file. Different operations that can be performed on a file are: i) Creation of a new file (fopen with attributes as “a” or “a+” or “w” or “wit. i ii) Opening an existing file (fopen). iii) Reading from file (fscanf or fgete). iv) Writing to a file (fprintf or fputs). ¥) Moving to a specific location in a file (fseek, rewind). vi) Closing a file (fclose). ‘The text in the brackets denotes the functions used for performing those operations. 14.2.1 Mode of Operation: There are many modes for opening a file. Based on the file mode, it can be opened for reading or writing, or appending the texts, They are listed below. Problem Solving using Programming; 568 ne 1» Opens a file in read mode and sets a pointer to the first character in the returns NULL if the file does not exist. @ w-> Opens a file in write mode. It returns NULL if the file could not be ope, the file exists, data are overwritten. @ 2 Opens a file in append mode. It returns NULL if the file cannot be opened, @ r+ Opens a file for read and write mode and sets a pointer to the first ch, in the file. © w+ Opens a file for read and write mode and sets a pointer to the first in the file. file. 1p ned. Ip aracter character @ at— Opens a file for read and write mode and sets the pointer to the fir st character in the file, But it cannot modify existing content. 14.2.2 File Input/Output A file represents a sequence of bytes on the disk where a group of related data is stored, The file is created for permanent storage of data. It is a readymade structure. In C language, we use a structure pointer of the file type to declare a file. FILE *fp; C provides several functions that help to the functions, Table 14.1: Different Functions of File perform basic file operations. The following are Function Description fopend create a new file or open an existing file felosed closes a file getc) reads a character from a file puted) writes a character to a file fscanf0) reads a set of data from a file fprintfQ writes a set of data to a file getw) reads an integer from a file putw() writes an integer to a file fseek0) set the position to the desired point [" fretio gives the current position in the file rewind() set the position to the beginning point 14.2.8 Opening a File ‘The fopen( function is used to create a new file or to open an existing file. General Syntax: “fp = FILE “fopen(const char “filename, const char *mode); i er Handling a * i i 569 __ fp is the FILE pointer (FILE *ép), which will hold the reference to eres“ ed or created. The filename is the name of the file to be opened the file that ste Pe pose of opening the file, The mode can be of the following athe mode fis Uggs List of File Mode with their explanation a rable 14 Xr The opening mode in Standard VO LT Description During the inexistence of file qpens a text file in reading mode | If the file does not exist, fopend ret r NULL. turns mal opens or creates a text file in If the file exists, its contents are writing mode. overwritten. If the file does not exist, it will be created. A opens a text file in append mode, ~ [if the file does not exist, it will be ie, data is added to the end of created. the file. a opens a text file in both reading If the file does not exist, fopen() returns and writing mode NULL. Gr] opens a text file in both reading | If the file exists, its contents are and writing mode overwritten. If the file does not exist, it will be created. at opens a text file in both reading If the file does not exist, it will be and writing mode | created, 1b opens a binary file in reading mode | If the file does not exist, fopen0 returns NULL. wb opens or creates a binary file in lie the file exists, its contents are writing mode overwritten. If the file does not exist, _| it will be created. ab opens a binary file in append mode | If the file does not exist, it will be created. tht | opens a binary file in both reading | Ifthe file does not exis, fopen0 returns and writing mode NULL. wot | opens a binary file in both reading | If the file exists, its contents 0 and writing mode overwritten. If the file does n°! xist, it will be created. abt ~ i | be opens a binary file in both reading | If the file does mot exist wil and appending in binary mode created. Problem Solving using p, 0 ra - ng a File: ming si 142 Clo 1 function is used to close an already opened file, : ja The fel smitax: General Sy7 : int folose(FILE *fP)s 1 function closes the file and returns zero on success Here ee the file. This EOF is a constant defined in the head n clos il? or EOF ig the : ler file stig’ a, o oh, Working with files: When working with files, we need to declare a pointer of the type file, c sg This "Jed for communication between the file and the program, delat, is nee FILE *fptrs 14.2.5 Opening a File for Creation and Edit: AA file is opened using the library function in the "stdio.h” header file: fopeng, ‘The syntax for opening a file in standard /O is: ”,"mode"); ptr = fopen(“fileopen”, For example: fopen(“E:\\cprogram\\newprogram.txt”,"w"); fopen(“E:\\cprogram\\oldprogram.bin”,”rb”); @ Let us suppose the file newprogram.txt does not exist in the location EA program, The first function creates a new file named newprogram.txt and opens it for writ as per the mode ‘w’. The writing mode allows us to create and edit (overnite) the file’s contents. © Suppose the second binary file, oldprogram.bin, exists in the location E:\cprogran. The second function opens the existing file for reading in binary mode ‘rb’. @ The reading mode only allows us to read the file; we cannot write into the file. 14.2.6 Reading from a File ‘The file read operations can be performed using functions fscanf() or fgets(. Both functions performed the same operations as printf and get but with an additional parameter, the file Pointer. So, it depends on whether we want to read the file line by line or character by character. Moreover, the code snippet for reading a file is as FILE * fp; fp = fopen(‘fileName.txt’, “r”); fecanf(fp, “%s %s %s %d”, str1, str2, str3, &year); 14.2.7 Writing into a File: The file write operation can be to read operations. The snippet fo FILE “fp ; performed by the functions fprintf() and fputs0, similar r writing to a file is as follows: “ pandli s pe fopent*fileName.tt”, “w"); iit “36s %s %s %d", “We”, “are”, “in”, 2012); rosin # file: vr every successful fie operation, we must always close a file. For closing a file, we ‘ase feloseQ function. The snippet for closing a file is given as: FILE *fP 5 pe open ileName.txt", Ww"); Some file operations _— selose(tP) {Reading and writing to a text file Wo use the functions fprint{0 and fscanf0) for reading and writing to a text file. They are Wipe file versions of printf) and scanf0. The only difference is that fprintO and fscanf) iix a pointer to the structure FILE. "e Writing into a text file Example 1: Write to @ text file using fprintf #include int mainO { int num; FILE *fptr; ftr = fopen(*C:\\program.txt”,“w"); if (ptr == NULL) { printf(“Error!”); exit(); } printf(“Enter num: seanf(“%d", &num); fprintf(fptr,“%d” num); felose(fptr); return 0; } This program takes a number from the user and stores it in the file program.txt. After y compile and run this program, we can see a text file program.txt created in the C drive ‘our computer. When we open the file, we can see the integer we entered. Reading from a text file: Example 2: Read from a text file using fscanf() finclude int maing, ee 572 Problem Solving Using Program ming in: int num; FILE *fptr; if ((fptr = fopen(“C:\\program.txt’,"r’)) == NULL){ printf("Error! opening file”); i/program exits if the file pointer returns NULL. exit(1); } fscanf(fptr,“%d”, &num); printf(“Value of n=%d”, num); felose(fptr); return 0; } This program reads the integer in the program.txt file and prints it onto the screen, jf we successfully create the file from Example 1, running this program will get us the integer we entered. Other functions like fgetchar0, fputcQ, etc., can be used similarly + Reading and writing to a binary file: Functions fread( and fwrite( are used for reading from and writing to a file on the disk respectively, in the case of binary files. . + Writing to a binary file: We need to use the function fwrite( to write into a binary file. The function takes four arguments: Address of data to be written on disk, size of data to be written on disk, number of such type of data, and a pointer to the file where we want to write. fwrite(address_data,size_data,numbers_data,pointer_to_file); Example 3: Writing to a binary file using fwriteQ #include struct threeNum { int nl, n2, 3; h int main { int n; struct threeNum num; FILE *fptr; if ((fptr = fopen(“C:\\program.bin”,“wb”)) = NULL){ printf(‘Error! opening file”); A lire ‘ le 673 program exits if the Ble pointe ¥ returns NULL. exit(): Mane kn <5; Hn) iv * yum.nl = 0; pum.n2 = Bn; pum.n3 = 6n + 1; fwrite(&num, sizeof(struct threeNum), 1, fptr); 4 felose(fptr); return 0; } Inthis program, we create a new file program.bin in the C drive. We declare a structure «{tiree Num with three numbers - n1, n2, and n3, and define it in the main function as sum. We store the value in the file using the fwrite function written within the for loop. jhe first parameter takes the address of num, and the second takes the size of the gructure threeNum. Since we are only inserting one instance of num, the third parameter is1, Moreover, the last parameter *fptr points to the file we are storing the data. Finally, se close the file. ¢ Reading from a binary file: Function fread() also takes 4 arguments similar to fwrite() function as above. fread(address_data,size_datanumbers_data,pointer_to_file); ¢ Example 4: Reading from a binary file using fread(Q) #include struct threeNum ( int nl, n2, n3; h int main) { int n; struct threeNum num; FILE *fptr; if ((fptr = fopen(“C:\\program.bin”,“rb”)) == NULL){ printf(“Error! opening file”); Mprogram exits if the file pointer returns NULL. exit(1); } for(n = 1; n < 5; ++n) (oe OY Problem Solving using Pro, Bid eraMMing in . { fread(&num, sizeof(struct threeNum), 1, fptr); printi(int: 9ed\tn2: %d\tn3: %d”, num.n1, num.n2, num.n3); } felose(fptr); return 0; } In this program, we read the same file program.bin and loop through the records ong one. In simple terms, we read one threeNum record of threeNum size from the file Pointeg by “{ptr into the structure num. 14.2.8 Getting Data using fseek(): If we have many records inside a file and need to access a record at a specific postin, we need to loop through all the records before it to get the record. It will waste a lot of memory and operation time. An easier way to get to the required data can be achieve using fseek(). As the name suggests, fseek() seeks the cursor to the given record in the file, ~ Syntax of fseek(): fseek(FILE * stream, long int offset, int whence); The first parameter stream is the pointer to the file. The second parameter is the position of the record to be found, and the third parameter specifies the location where the offset starts. Table 14.3: Contents of fseek() function Different whence in fseek() Whence Meaning SEKK_SET | Starts the offset from the beginning of the file. SEKK_END | Starts the offset from the end of the file. SEKK_CUR Starts the offset from the current location of the cursor in the file. Example of fseek(): #include struct threeNum i { int nl, n2, n3; ’ int main { int n; fie Handling struct threeNum num; 575 FILE *fptr: if (ptr = fopen(“C:\\program.bin" print{(‘Error! inprogram exits if the file pointer returns NULL. rb") == NULL) pening file”); exit(L); } 1 Mov feock(ptr, sizeofistruct threeNum), SEEK_END); for(n = 1; 9 < 5; +n) ( fread(&num, s printf(inl: %d\tn2: } felose(fptr); return 0; } ‘This program will st reverse order (last to first). ¢ fiell0 - It tells the byte loc: pointer. # rewind - It moves the control to the es the cursor to the end of the file ‘izeof(struct threeNum), 1, fptr); %d\tn3: %d”, num.n1, num.n2, num.n3); tart reading and printing the records from the file program.bin in lation of the cursor’s current position in the file beginning of the file. gram exits. Normally we use a variable or Itwill contain the data even after the pro and arrays are non- aay to store data, but data is lost after the program exits. Variables Yermanent storage mediums, whereas the file is permanent. jipend|and Write mode seit) mode and Append (@) mode while opening a file are almost identical. Both are oie in a file. In both modes, a new file is created if it does not exist. The only ihe delet y have is that when we open a file in the write mode, the file is reset, resulting eae of any data already present in the file. While in append mode, this will not rt Anpend mode is used to append or add data to the existing data of the file Gf any). erie We open a file in append (a) mode, the cursor is positioned at the end of the in the file.

You might also like