Read File Until End of File C++
C File management
A File tin can exist used to store a big volume of persistent data. Similar many other languages 'C' provides following file management functions,
- Cosmos of a file
- Opening a file
- Reading a file
- Writing to a file
- Closing a file
Post-obit are the most important file direction functions bachelor in 'C,'
function | 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 grapheme 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 current position of a file pointer | |
rewind () | Sets the file pointer at the beginning of a file |
In this tutorial, y'all volition acquire-
- How to Create a File
- How to Shut a file:
- Writing to a File
- fputc() Function:
- fputs () Part:
- fprintf()Role:
- Reading data from a File
- Interactive File Read and Write with getc and putc
How to Create a File
Whenever yous desire to piece of work with a file, the first step is to create a file. A file is nothing but space in a memory where information is stored.
To create a file in a 'C' programme post-obit syntax is used,
FILE *fp; fp = fopen ("file_name", "way");
In the higher up syntax, the file is a data structure which is defined in the standard library.
fopen is a standard role which is used to open up a file.
- If the file is not present on the organisation, then it is created then opened.
- If a file is already present on the system, so it is directly opened using this function.
fp is a file arrow which points to the blazon file.
Whenever you open or create a file, you lot have to specify what you are going to do with the file. A file in 'C' programming can be created or opened for reading/writing purposes. A style is used to specify whether you want to open a file for any of the below-given purposes. Post-obit are the different types of modes in 'C' programming which tin can be used while working with a file.
File Mode | Description |
---|---|
r | Open up a file for reading. If a file is in reading mode, then no data is deleted if a file is already present on a organisation. |
w | Open up a file for writing. If a file is in writing mode, then a new file is created if a file doesn't be at all. If a file is already nowadays on a organization, then all the data inside the file is truncated, and information technology is opened for writing purposes. |
a | Open up a file in append way. If a file is in append mode, then the file is opened. The content within the file doesn't change. |
r+ | open for reading and writing from get-go |
w+ | open for reading and writing, overwriting a file |
a+ | open up for reading and writing, appending to file |
In the given syntax, the filename and the mode are specified as strings hence they must always exist enclosed inside double quotes.
Example:
#include <stdio.h> int main() { FILE *fp; fp = fopen ("information.txt", "w"); }
Output:
File is created in the same folder where you have saved your lawmaking.
You can specify the path where you want to create your file
#include <stdio.h> int primary() { FILE *fp; fp = fopen ("D://data.txt", "w"); }
How to Close a file
Ane should e'er shut a file whenever the operations on file are over. Information technology means the contents and links to the file are terminated. This prevents accidental damage to the file.
'C' provides the fclose office to perform file closing performance. The syntax of fclose is equally follows,
fclose (file_pointer);
Example:
FILE *fp; fp = fopen ("data.txt", "r"); fclose (fp);
The fclose function takes a file arrow every bit an argument. The file associated with the file pointer is and 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 endmost.
Afterwards closing the file, the same file pointer can also be used with other files.
In 'C' programming, files are automatically close when the program is terminated. Closing a file manually by writing fclose part is a good programming practise.
Writing to a File
In C, when you lot write to a file, newline characters '\n' must exist 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 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): It prints a string to the file pointed to by file_pointer. The cord can optionally include format specifiers and a listing of variables variable_lists.
The program beneath shows how to perform writing to a file:
fputc() Function:
#include <stdio.h> int main() { int i; FILE * fptr; char fn[50]; char str[] = "Guru99 Rocks\north"; fptr = fopen("fputc_test.txt", "west"); // "westward" defines "writing mode" for (i = 0; str[i] != '\northward'; i++) { /* write to file using fputc() function */ fputc(str[i], fptr); } fclose(fptr); return 0; }
Output:
The higher up plan writes a single character into the fputc_test.txt file until it reaches the next line symbol "\northward" which indicates that the sentence was successfully written. The procedure is to accept each character of the array and write it into the file.
- In the above program, we accept created and opened a file chosen fputc_test.txt in a write mode and declare our string which will be written into the file.
- Nosotros do a character by grapheme write operation using for loop and put each character in our file until the "\due north" character is encountered then the file is closed using the fclose function.
fputs () Part:
#include <stdio.h> int primary() { FILE * fp; fp = fopen("fputs_test.txt", "w+"); fputs("This is Guru99 Tutorial on fputs,", fp); fputs("Nosotros don't need to utilise for loop\north", fp); fputs("Easier than fputc function\n", fp); fclose(fp); return (0); }
OUTPUT:
- In the above plan, we accept created and opened a file called fputs_test.txt in a write mode.
- Subsequently we practise a write operation using fputs() function past writing iii different strings
- Then the file is closed using the fclose function.
fprintf()Function:
#include <stdio.h> int main() { 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 above program we have created and opened a file called fprintf_test.txt in a write way.
- Later on a write operation is performed using fprintf() function by writing a string, then the file is closed using the fclose function.
Reading data from a File
In that location are three dissimilar functions dedicated to reading data from a file
- fgetc(file_pointer): It returns the next character from the file pointed to past the file pointer. When the finish of the file has been reached, the EOF is sent dorsum.
- fgets(buffer, n, file_pointer): It reads n-1 characters from the file and stores the cord in a buffer in which the Aught character '\0' is appended as the terminal character.
- fscanf(file_pointer, conversion_specifiers, variable_adresses): It is used to parse and analyze information. It reads characters from the file and assigns the input to a list of variable pointers variable_adresses using conversion specifiers. Proceed in mind that as with scanf, fscanf stops reading a string when space or newline is encountered.
The following plan demonstrates reading from fputs_test.txt file using fgets(),fscanf() and fgetc () functions respectively :
#include <stdio.h> int primary() { FILE * file_pointer; char buffer[thirty], c; file_pointer = fopen("fprintf_test.txt", "r"); printf("----read a line----\n"); fgets(buffer, l, file_pointer); printf("%south\north", buffer); printf("----read and parse data----\n"); file_pointer = fopen("fprintf_test.txt", "r"); //reset the pointer char str1[x], str2[2], str3[20], str4[2]; fscanf(file_pointer, "%s %southward %south %southward", str1, str2, str3, str4); printf("Read String1 |%s|\northward", str1); printf("Read String2 |%due south|\n", str2); printf("Read String3 |%s|\due north", str3); printf("Read String4 |%due south|\n", str4); printf("----read the unabridged 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; }
Outcome:
----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 unabridged file---- Learning C with Guru99
- In the above program, we take opened the file called "fprintf_test.txt" which was previously written using fprintf() part, and it contains "Learning C with Guru99" string. We read it using the fgets() part which reads line by line where the buffer size must exist plenty to handle the entire line.
- We reopen the file to reset the pointer file to point at the beginning of the file. Create various strings variables to handle each word separately. Impress the variables to see their contents. The fscanf() is mainly used to extract 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 performance file using unlike variants, we again airtight 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 ii functions are used to handle but a single character at a fourth dimension.
Following program demonstrates the file handling functions in 'C' programming:
#include <stdio.h> int main() { FILE * fp; char c; printf("File Treatment\northward"); //open up 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); return 0; }
Output:
- In the above program we have created and opened a file chosen demo in a write mode.
- Afterwards a write operation is performed, then the file is closed using the fclose function.
- Nosotros take again opened a file which now contains data in a reading mode. A while loop will execute until the eof is found. Once the end of file is found the operation will be terminated and data will be displayed using printf function.
- Afterward performing a reading functioning file is once more closed using the fclose function.
Summary
- A file is a space in a retention where data is stored.
- 'C' programming provides diverse 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 suspend style.
- Getc and putc functions are used to read and write a single character.
- The office fscanf() permits to read and parse data from a file
- We can read (using the getc function) an unabridged file by looping to cover all the file until the EOF is encountered
- Nosotros can write to a file after creating its name, by using the office fprintf() and it must take the newline grapheme at the end of the cord text.
Source: https://www.guru99.com/c-file-input-output.html
Belum ada Komentar untuk "Read File Until End of File C++"
Posting Komentar