How to Read a File and Output the Data in C++
C File management
A File can be used to store a large volume of persistent data. Like many other languages 'C' provides following file direction functions,
- Cosmos of a file
- Opening a file
- Reading a file
- Writing to a file
- Closing a file
Following are the nearly important file management functions bachelor in 'C,'
office | purpose | |
---|---|---|
fopen () | Creating a file or opening an existing file | |
fclose () | Closing 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 single character 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 electric current position of a file pointer | |
rewind () | Sets the file pointer at the commencement of a file |
In this tutorial, y'all will acquire-
- How to Create a File
- How to Close a file:
- Writing to a File
- fputc() Function:
- fputs () Office:
- fprintf()Function:
- Reading data from a File
- Interactive File Read and Write with getc and putc
How to Create a File
Whenever yous want to piece of work with a file, the first stride is to create a file. A file is nix but infinite in a memory 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 in a higher place syntax, the file is a information structure which is defined in the standard library.
fopen is a standard function which is used to open a file.
- If the file is non present on the system, and then information technology is created and then opened.
- If a file is already present on the organisation, then it is directly opened using this part.
fp is a file arrow which points to the type file.
Whenever y'all open or create a file, you take to specify what y'all are going to do with the file. A file in 'C' programming tin be created or opened for reading/writing purposes. A mode is used to specify whether y'all want to open a file for any of the below-given purposes. Following are the unlike types of modes in 'C' programming which can be used while working with a file.
File Fashion | Description |
---|---|
r | Open a file for reading. If a file is in reading manner, then no data is deleted if a file is already present on a system. |
due west | Open a file for writing. If a file is in writing mode, then a new file is created if a file doesn't exist at all. If a file is already present on a system, and then all the data inside the file is truncated, and information technology is opened for writing purposes. |
a | Open up a file in suspend mode. If a file is in append manner, and so the file is opened. The content within the file doesn't alter. |
r+ | open up for reading and writing from beginning |
westward+ | 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 mode are specified as strings hence they must ever be enclosed within double quotes.
Example:
#include <stdio.h> int main() { FILE *fp; fp = fopen ("information.txt", "west"); }
Output:
File is created in the same folder where yous have saved your code.
You can specify the path where you lot desire to create your file
#include <stdio.h> int principal() { FILE *fp; fp = fopen ("D://data.txt", "westward"); }
How to Close a file
1 should ever close a file whenever the operations on file are over. Information technology means the contents and links to the file are terminated. This prevents accidental impairment to the file.
'C' provides the fclose function to perform file closing operation. The syntax of fclose is equally follows,
fclose (file_pointer);
Instance:
FILE *fp; fp = fopen ("information.txt", "r"); fclose (fp);
The fclose function takes a file arrow as an argument. The file associated with the file arrow is then closed with the help of fclose function. It returns 0 if close was successful and EOF (end of file) if there is an mistake has occurred while file closing.
Afterward closing the file, the aforementioned file pointer tin can likewise be used with other files.
In 'C' programming, files are automatically close when the program is terminated. Closing a file manually by writing fclose function is a adept programming practice.
Writing to a File
In C, when yous 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 character to the file pointed to past file_pointer.
- fputs(str, file_pointer): It writes a string to the file pointed to by file_pointer.
- fprintf(file_pointer, str, variable_lists): It prints a cord to the file pointed to by file_pointer. The cord can optionally include format specifiers and a listing of variables variable_lists.
The programme below shows how to perform writing to a file:
fputc() Function:
#include <stdio.h> int main() { int i; FILE * fptr; char fn[l]; char str[] = "Guru99 Rocks\n"; fptr = fopen("fputc_test.txt", "w"); // "westward" defines "writing fashion" for (i = 0; str[i] != '\north'; i++) { /* write to file using fputc() role */ fputc(str[i], fptr); } fclose(fptr); render 0; }
Output:
The in a higher place program writes a unmarried character into the fputc_test.txt file until information technology reaches the next line symbol "\due north" which indicates that the judgement was successfully written. The process is to take each character of the array and write it into the file.
- In the to a higher place program, we have created and opened a file called fputc_test.txt in a write style and declare our cord which will be written into the file.
- We practice a character by character write operation using for loop and put each grapheme in our file until the "\n" graphic symbol is encountered and so the file is closed using the fclose office.
fputs () Function:
#include <stdio.h> int main() { FILE * fp; fp = fopen("fputs_test.txt", "west+"); fputs("This is Guru99 Tutorial on fputs,", fp); fputs("We don't need to use for loop\n", fp); fputs("Easier than fputc function\due north", fp); fclose(fp); render (0); }
OUTPUT:
- In the above plan, nosotros have created and opened a file chosen fputs_test.txt in a write way.
- After we do a write operation using fputs() function past writing three dissimilar strings
- So the file is closed using the fclose function.
fprintf()Role:
#include <stdio.h> int principal() { FILE *fptr; fptr = fopen("fprintf_test.txt", "w"); // "w" defines "writing mode" /* write to file */ fprintf(fptr, "Learning C with Guru99\n"); fclose(fptr); render 0; }
OUTPUT:
- In the to a higher place program we have created and opened a file chosen fprintf_test.txt in a write mode.
- After a write operation is performed using fprintf() function by writing a string, then the file is closed using the fclose role.
Reading data from a File
There are three different functions dedicated to reading data from a file
- fgetc(file_pointer): It returns the next grapheme from the file pointed to by the file arrow. When the end of the file has been reached, the EOF is sent back.
- fgets(buffer, northward, file_pointer): It reads n-1 characters from the file and stores the string in a buffer in which the Zip graphic symbol '\0' is appended as the terminal graphic symbol.
- 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. Keep in mind that every bit with scanf, fscanf stops reading a cord when space or newline is encountered.
The following program demonstrates reading from fputs_test.txt file using fgets(),fscanf() and fgetc () functions respectively :
#include <stdio.h> int main() { FILE * file_pointer; char buffer[30], c; file_pointer = fopen("fprintf_test.txt", "r"); printf("----read a line----\n"); fgets(buffer, 50, file_pointer); printf("%southward\n", buffer); printf("----read and parse data----\north"); file_pointer = fopen("fprintf_test.txt", "r"); //reset the pointer char str1[10], str2[two], str3[twenty], str4[two]; fscanf(file_pointer, "%south %s %s %due south", str1, str2, str3, str4); printf("Read String1 |%s|\north", str1); printf("Read String2 |%due south|\north", str2); printf("Read String3 |%due south|\north", str3); printf("Read String4 |%due south|\northward", str4); printf("----read the entire file----\n"); file_pointer = fopen("fprintf_test.txt", "r"); //reset the pointer 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 programme, we have 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 exist enough to handle the unabridged line.
- We reopen the file to reset the pointer file to indicate at the beginning of the file. Create various strings variables to handle each word separately. Impress the variables to run into their contents. The fscanf() is mainly used to extract and parse information 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 graphic symbol by character using getc() role until the EOF statement is encountered
- After performing a reading operation file using different variants, nosotros over 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 go character, and putc stands for put character. These two functions are used to handle only a single character at a time.
Following plan demonstrates the file handling functions in 'C' programming:
#include <stdio.h> int main() { FILE * fp; char c; printf("File Treatment\due north"); //open a file fp = fopen("demo.txt", "w"); //writing operation while ((c = getchar()) != EOF) { putc(c, fp); } //close file fclose(fp); printf("Data Entered:\northward"); //reading fp = fopen("demo.txt", "r"); while ((c = getc(fp)) != EOF) { printf("%c", c); } fclose(fp); render 0; }
Output:
- In the in a higher place programme we have created and opened a file called demo in a write mode.
- After a write operation is performed, then the file is closed using the fclose function.
- We have over again opened a file which now contains data in a reading mode. A while loop will execute until the eof is found. In one case the end of file is institute the operation will be terminated and data volition be displayed using printf role.
- Afterwards performing a reading operation file is once again closed using the fclose role.
Summary
- A file is a infinite in a memory where information is stored.
- 'C' programming provides various functions to deal with a file.
- A mechanism of manipulating with the files is called as file management.
- A file must be opened before performing operations on information technology.
- A file can exist opened in a read, write or an append way.
- Getc and putc functions are used to read and write a single character.
- The role fscanf() permits to read and parse data from a file
- We can read (using the getc function) an entire file past looping to cover all the file until the EOF is encountered
- We can write to a file later creating its proper name, by using the part fprintf() and it must take the newline character at the cease of the string text.
Source: https://www.guru99.com/c-file-input-output.html
0 Response to "How to Read a File and Output the Data in C++"
Post a Comment