C Read Integer From File Until End of File
C File management
A File can exist used to shop a big book of persistent data. Similar many other languages 'C' provides following file management functions,
- Creation of a file
- Opening a file
- Reading a file
- Writing to a file
- Endmost 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 information to a file | |
fscanf () | Reading a block data from a file | |
getc () | Reads a single character from a file | |
putc () | Writes a unmarried 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, you will learn-
- How to Create a File
- How to Shut a file:
- Writing to a File
- fputc() Role:
- fputs () Function:
- fprintf()Function:
- 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 first pace is to create a file. A file is nothing but infinite in a retention where information is stored.
To create a file in a 'C' program following syntax is used,
FILE *fp; fp = fopen ("file_name", "mode");
In the to a higher place syntax, the file is a data structure which is defined in the standard library.
fopen is a standard office which is used to open a file.
- If the file is non present on the organization, then it is created and and so opened.
- If a file is already present on the organization, then it is directly opened using this function.
fp is a file pointer which points to the type file.
Whenever you open or create a file, y'all accept to specify what you are going to practice with the file. A file in 'C' programming can exist created or opened for reading/writing purposes. A mode is used to specify whether you lot desire to open a file for whatever of the below-given purposes. Following are the unlike types of modes in 'C' programming which tin be used while working with a file.
File Way | Description |
---|---|
r | Open a file for reading. If a file is in reading fashion, then no information is deleted if a file is already present on a system. |
west | Open a file for writing. If a file is in writing manner, then a new file is created if a file doesn't exist at all. If a file is already present on a system, then all the data inside the file is truncated, and information technology is opened for writing purposes. |
a | Open up a file in append manner. If a file is in append fashion, and so the file is opened. The content within the file doesn't alter. |
r+ | open for reading and writing from beginning |
w+ | 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 every bit strings hence they must e'er exist enclosed within double quotes.
Case:
#include <stdio.h> int main() { FILE *fp; fp = fopen ("data.txt", "w"); }
Output:
File is created in the aforementioned folder where yous have saved your code.
Y'all tin specify the path where y'all desire to create your file
#include <stdio.h> int master() { FILE *fp; fp = fopen ("D://data.txt", "westward"); }
How to Close a file
One should always close a file whenever the operations on file are over. It means the contents and links to the file are terminated. This prevents accidental damage to the file.
'C' provides the fclose function to perform file endmost operation. The syntax of fclose is as follows,
fclose (file_pointer);
Case:
FILE *fp; fp = fopen ("data.txt", "r"); fclose (fp);
The fclose office takes a file pointer as an argument. The file associated with the file pointer is then closed with the aid of fclose function. It returns 0 if close was successful and EOF (finish of file) if there is an error has occurred while file closing.
Later closing the file, the same file pointer can as well exist 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 good programming practice.
Writing to a File
In C, when yous write to a file, newline characters '\north' must be explicitly added.
The stdio library offers the necessary functions to write to a file:
- fputc(char, file_pointer): It writes a graphic symbol to the file pointed to by file_pointer.
- fputs(str, file_pointer): Information technology writes a cord 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 string tin optionally include format specifiers and a list of variables variable_lists.
The plan below shows how to perform writing to a file:
fputc() Office:
#include <stdio.h> int chief() { int i; FILE * fptr; char fn[50]; char str[] = "Guru99 Rocks\n"; fptr = fopen("fputc_test.txt", "west"); // "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 to a higher place program writes a unmarried character into the fputc_test.txt file until it reaches the next line symbol "\n" which indicates that the sentence was successfully written. The process is to accept each character of the array and write it into the file.
- In the above program, nosotros take 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 grapheme by grapheme write performance using for loop and put each character in our file until the "\north" character is encountered and so the file is closed using the fclose function.
fputs () Function:
#include <stdio.h> int chief() { FILE * fp; fp = fopen("fputs_test.txt", "w+"); fputs("This is Guru99 Tutorial on fputs,", fp); fputs("We don't need to employ for loop\n", fp); fputs("Easier than fputc function\due north", fp); fclose(fp); return (0); }
OUTPUT:
- In the higher up program, we have created and opened a file called fputs_test.txt in a write mode.
- After we do a write performance using fputs() function by writing three 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); return 0; }
OUTPUT:
- In the above program we have created and opened a file called fprintf_test.txt in a write mode.
- Afterward a write operation is performed using fprintf() function by writing a string, so the file is airtight using the fclose role.
Reading data from a File
In that location are three unlike functions dedicated to reading data from a file
- fgetc(file_pointer): It returns the side by side graphic symbol from the file pointed to by the file pointer. When the end of the file has been reached, the EOF is sent back.
- fgets(buffer, north, file_pointer): Information technology reads n-1 characters from the file and stores the string in a buffer in which the NULL graphic symbol '\0' is appended as the final graphic symbol.
- fscanf(file_pointer, conversion_specifiers, variable_adresses): It is used to parse and clarify information. It reads characters from the file and assigns the input to a list of variable pointers variable_adresses using conversion specifiers. Keep in listen that as with scanf, fscanf stops reading a string 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[xxx], c; file_pointer = fopen("fprintf_test.txt", "r"); printf("----read a line----\n"); fgets(buffer, 50, file_pointer); printf("%south\north", buffer); printf("----read and parse data----\north"); file_pointer = fopen("fprintf_test.txt", "r"); //reset the arrow char str1[10], str2[2], str3[20], str4[2]; fscanf(file_pointer, "%s %s %s %s", str1, str2, str3, str4); printf("Read String1 |%southward|\n", str1); printf("Read String2 |%s|\northward", str2); printf("Read String3 |%south|\due north", str3); printf("Read String4 |%s|\n", 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); render 0; }
Result:
----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" cord. We read it using the fgets() function which reads line by line where the buffer size must be plenty to handle the entire line.
- Nosotros reopen the file to reset the arrow file to indicate at the offset of the file. Create various strings variables to handle each discussion 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 arrow file to point at the outset of the file. Read data and print it from the file graphic symbol by grapheme using getc() function until the EOF statement is encountered
- Afterward performing a reading operation file using different 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 grapheme, and putc stands for put character. These two functions are used to handle simply a single character at a time.
Following program demonstrates the file handling functions in 'C' programming:
#include <stdio.h> int master() { FILE * fp; char c; printf("File Handling\n"); //open a file fp = fopen("demo.txt", "westward"); //writing operation while ((c = getchar()) != EOF) { putc(c, fp); } //close file fclose(fp); printf("Information Entered:\north"); //reading fp = fopen("demo.txt", "r"); while ((c = getc(fp)) != EOF) { printf("%c", c); } fclose(fp); return 0; }
Output:
- In the higher up program 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 role.
- We have once more opened a file which now contains data in a reading fashion. A while loop will execute until the eof is found. In one case the end of file is found the operation will be terminated and data will be displayed using printf function.
- Subsequently performing a reading operation file is again closed using the fclose part.
Summary
- A file is a space in a memory where information is stored.
- 'C' programming provides various functions to deal with a file.
- A machinery of manipulating with the files is called every bit file management.
- A file must be 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 grapheme.
- The role fscanf() permits to read and parse data from a file
- We can read (using the getc function) an unabridged file past looping to cover all the file until the EOF is encountered
- We tin can write to a file later on creating its name, by using the function fprintf() and information technology must have the newline grapheme at the finish of the string text.
Source: https://www.guru99.com/c-file-input-output.html