Function to Reopen File and Read Again
C File management
A File can be used to store a large volume of persistent data. Like many other languages 'C' provides following file management functions,
- Cosmos of a file
- Opening a file
- Reading a file
- Writing to a file
- Endmost a file
Following are the well-nigh important file management functions bachelor in 'C,'
function | purpose | |
---|---|---|
fopen () | Creating a file or opening an existing file | |
fclose () | Endmost a file | |
fprintf () | Writing a block of data to a file | |
fscanf () | Reading a block data from a file | |
getc () | Reads a single character from a file | |
putc () | Writes a unmarried graphic symbol to a file | |
getw () | Reads an integer from a file | |
putw () | Writing an integer to a file | |
fseek () | Sets the position of a file pointer to a specified location | |
ftell () | Returns the current position of a file arrow | |
rewind () | Sets the file arrow at the beginning of a file |
In this tutorial, you lot will learn-
- How to Create a File
- How to Shut a file:
- Writing to a File
- fputc() Role:
- fputs () Role:
- fprintf()Office:
- Reading data from a File
- Interactive File Read and Write with getc and putc
How to Create a File
Whenever you want to work with a file, the commencement step is to create a file. A file is nothing but space in a retentivity where data is stored.
To create a file in a 'C' program following syntax is used,
FILE *fp; fp = fopen ("file_name", "mode");
In the above syntax, the file is a data construction which is divers in the standard library.
fopen is a standard role which is used to open a file.
- If the file is not nowadays on the system, then it is created and so opened.
- If a file is already present on the organization, then information technology is straight opened using this role.
fp is a file pointer which points to the blazon file.
Whenever you open or create a file, you have to specify what yous are going to exercise with the file. A file in 'C' programming tin can be created or opened for reading/writing purposes. A mode is used to specify whether you want to open a file for any of the below-given purposes. Following are the different types of modes in 'C' programming which tin can be used while working with a file.
File Mode | Clarification |
---|---|
r | Open a file for reading. If a file is in reading mode, then no data is deleted if a file is already present on a system. |
w | Open a file for writing. If a file is in writing way, so a new file is created if a file doesn't be at all. If a file is already present on a arrangement, then all the information inside the file is truncated, and it is opened for writing purposes. |
a | Open up a file in append mode. If a file is in append style, so the file is opened. The content within the file doesn't change. |
r+ | open for reading and writing from outset |
due west+ | open for reading and writing, overwriting a file |
a+ | open for reading and writing, appending to file |
In the given syntax, the filename and the way are specified equally strings hence they must ever be enclosed within double quotes.
Example:
#include <stdio.h> int main() { FILE *fp; fp = fopen ("data.txt", "w"); }
Output:
File is created in the aforementioned folder where you have saved your code.
You can specify the path where you want to create your file
#include <stdio.h> int master() { FILE *fp; fp = fopen ("D://data.txt", "w"); }
How to Close a file
Ane should always close a file whenever the operations on file are over. It ways the contents and links to the file are terminated. This prevents accidental harm to the file.
'C' provides the fclose function to perform file closing operation. The syntax of fclose is every bit follows,
fclose (file_pointer);
Example:
FILE *fp; fp = fopen ("data.txt", "r"); fclose (fp);
The fclose function takes a file pointer as an argument. The file associated with the file pointer is so closed with the help of fclose function. It returns 0 if close was successful and EOF (end of file) if there is an error has occurred while file closing.
After closing the file, the aforementioned file pointer can also exist used with other files.
In 'C' programming, files are automatically close when the programme is terminated. Closing a file manually past writing fclose function is a expert programming practice.
Writing to a File
In C, when you write to a file, newline characters '\n' must be explicitly added.
The stdio library offers the necessary functions to write to a file:
- fputc(char, file_pointer): It writes a grapheme to the file pointed to by file_pointer.
- fputs(str, file_pointer): It writes a string to the file pointed to by file_pointer.
- fprintf(file_pointer, str, variable_lists): Information technology prints a cord to the file pointed to by file_pointer. The cord can optionally include format specifiers and a list of variables variable_lists.
The program beneath shows how to perform writing to a file:
fputc() Function:
#include <stdio.h> int primary() { int i; FILE * fptr; char fn[l]; char str[] = "Guru99 Rocks\n"; fptr = fopen("fputc_test.txt", "westward"); // "due west" defines "writing mode" for (i = 0; str[i] != '\n'; i++) { /* write to file using fputc() function */ fputc(str[i], fptr); } fclose(fptr); return 0; }
Output:
The higher up programme writes a single character into the fputc_test.txt file until information technology reaches the adjacent line symbol "\north" which indicates that the sentence was successfully written. The procedure is to have each grapheme of the array and write information technology into the file.
- In the above plan, we accept created and opened a file called fputc_test.txt in a write mode and declare our cord which will be written into the file.
- We do a character by character write operation using for loop and put each grapheme in our file until the "\n" character is encountered then the file is closed using the fclose function.
fputs () Function:
#include <stdio.h> int master() { FILE * fp; fp = fopen("fputs_test.txt", "w+"); fputs("This is Guru99 Tutorial on fputs,", fp); fputs("We don't demand to use for loop\n", fp); fputs("Easier than fputc function\n", fp); fclose(fp); return (0); }
OUTPUT:
- In the above program, we have created and opened a file called fputs_test.txt in a write mode.
- After we practise a write performance using fputs() office by writing three different strings
- Then the file is closed using the fclose role.
fprintf()Part:
#include <stdio.h> int main() { FILE *fptr; fptr = fopen("fprintf_test.txt", "due west"); // "w" defines "writing mode" /* write to file */ fprintf(fptr, "Learning C with Guru99\n"); fclose(fptr); return 0; }
OUTPUT:
- In the above programme nosotros have created and opened a file called fprintf_test.txt in a write mode.
- After a write operation is performed using fprintf() role by writing a string, then the file is airtight using the fclose function.
Reading data from a File
There are 3 different functions dedicated to reading data from a file
- fgetc(file_pointer): It returns the next graphic symbol from the file pointed to past the file arrow. When the finish of the file has been reached, the EOF is sent back.
- fgets(buffer, n, file_pointer): It reads n-1 characters from the file and stores the string in a buffer in which the NULL character '\0' is appended as the concluding character.
- fscanf(file_pointer, conversion_specifiers, variable_adresses): It is used to parse and analyze data. It reads characters from the file and assigns the input to a list of variable pointers variable_adresses using conversion specifiers. Go on in heed that as with scanf, fscanf stops reading a cord when space or newline is encountered.
The following programme demonstrates reading from fputs_test.txt file using fgets(),fscanf() and fgetc () functions respectively :
#include <stdio.h> int main() { FILE * file_pointer; char buffer[xxx], c; file_pointer = fopen("fprintf_test.txt", "r"); printf("----read a line----\n"); fgets(buffer, 50, file_pointer); printf("%s\n", buffer); printf("----read and parse data----\n"); file_pointer = fopen("fprintf_test.txt", "r"); //reset the pointer char str1[x], str2[ii], str3[20], str4[2]; fscanf(file_pointer, "%s %s %due south %southward", str1, str2, str3, str4); printf("Read String1 |%s|\north", str1); printf("Read String2 |%south|\n", str2); printf("Read String3 |%s|\n", str3); printf("Read String4 |%due south|\north", str4); printf("----read the entire file----\n"); file_pointer = fopen("fprintf_test.txt", "r"); //reset the arrow while ((c = getc(file_pointer)) != EOF) printf("%c", c); fclose(file_pointer); return 0; }
Upshot:
----read a line---- Learning C with Guru99 ----read and parse data---- Read String1 |Learning| Read String2 |C| Read String3 |with| Read String4 |Guru99| ----read the entire file---- Learning C with Guru99
- In the above program, nosotros take opened the file called "fprintf_test.txt" which was previously written using fprintf() function, and it contains "Learning C with Guru99" string. Nosotros read it using the fgets() function which reads line by line where the buffer size must be enough to handle the entire line.
- We reopen the file to reset the pointer file to bespeak at the commencement of the file. Create various strings variables to handle each word separately. Print the variables to see their contents. The fscanf() is mainly used to excerpt and parse data from a file.
- Reopen the file to reset the pointer file to point at the beginning of the file. Read data and print it from the file character by character using getc() function until the EOF statement is encountered
- After performing a reading functioning file using different variants, we again closed the file using the fclose function.
Interactive File Read and Write with getc and putc
These are the simplest file operations. Getc stands for get character, and putc stands for put grapheme. These 2 functions are used to handle only a unmarried character at a fourth dimension.
Post-obit program demonstrates the file handling functions in 'C' programming:
#include <stdio.h> int main() { FILE * fp; char c; printf("File Handling\n"); //open a file fp = fopen("demo.txt", "w"); //writing operation while ((c = getchar()) != EOF) { putc(c, fp); } //close file fclose(fp); printf("Data Entered:\n"); //reading fp = fopen("demo.txt", "r"); while ((c = getc(fp)) != EOF) { printf("%c", c); } fclose(fp); render 0; }
Output:
- In the above program we have created and opened a file called demo in a write manner.
- After a write operation is performed, then the file is closed using the fclose function.
- We take again opened a file which now contains data in a reading way. A while loop volition execute until the eof is found. In one case the end of file is found the operation volition be terminated and data will be displayed using printf part.
- After performing a reading performance file is again closed using the fclose part.
Summary
- A file is a space in a memory where data is stored.
- 'C' programming provides various functions to deal with a file.
- A machinery of manipulating with the files is chosen every bit file management.
- A file must exist opened before performing operations on it.
- A file can be opened in a read, write or an append mode.
- Getc and putc functions are used to read and write a single character.
- The function fscanf() permits to read and parse information from a file
- We tin can read (using the getc function) an entire file by looping to cover all the file until the EOF is encountered
- We can write to a file after creating its name, past using the function fprintf() and it must have the newline graphic symbol at the end of the string text.
bergevinhanch1998.blogspot.com
Source: https://www.guru99.com/c-file-input-output.html
0 Response to "Function to Reopen File and Read Again"
Post a Comment