The last chapter explained the standard input and output devices handled by C programming language. This chapter cover how C programmers can create, open, close text or binary files for their data storage.
A file represents a sequence of bytes, regardless of it being a text file or a binary file. C programming language provides access on high level functions as well as low level (OS level) calls to handle file on your storage devices. This chapter will take you through the important calls for file management.
Opening Files
You can use the fopen( ) function to create a new file or to open an existing file. This call will initialize an object of the type FILE, which contains all the information necessary to control the stream. The prototype of this function call is as follows −
Here, filename is a string literal, which you will use to name your file, and access mode can have one of the following values −
Sr.No.
Mode & Description
1
Opens an existing text file for reading purpose.
Opens a text file for writing. If it does not exist, then a new file is created. Here your program will start writing content from the beginning of the file.
Opens a text file for writing in appending mode. If it does not exist, then a new file is created. Here your program will start appending content in the existing file content.
Opens a text file for both reading and writing.
Opens a text file for both reading and writing. It first truncates the file to zero length if it exists, otherwise creates a file if it does not exist.
Opens a text file for both reading and writing. It creates the file if it does not exist. The reading will start from the beginning but writing can only be appended.
If you are going to handle binary files, then you will use following access modes instead of the above mentioned ones −
Closing a File
To close a file, use the fclose( ) function. The prototype of this function is −
The fclose(-) function returns zero on success, or EOF if there is an error in closing the file. This function actually flushes any data still pending in the buffer to the file, closes the file, and releases any memory used for the file. The EOF is a constant defined in the header file stdio.h.
There are various functions provided by C standard library to read and write a file, character by character, or in the form of a fixed length string.
Writing a File
Following is the simplest function to write individual characters to a stream −
The function fputc() writes the character value of the argument c to the output stream referenced by fp. It returns the written character written on success otherwise EOF if there is an error. You can use the following functions to write a null-terminated string to a stream −
The function fputs() writes the string s to the output stream referenced by fp. It returns a non-negative value on success, otherwise EOF is returned in case of any error. You can use int fprintf(FILE *fp,const char *format, . ) function as well to write a string into a file. Try the following example.
Make sure you have /tmp directory available. If it is not, then before proceeding, you must create this directory on your machine.
When the above code is compiled and executed, it creates a new file test.txt in /tmp directory and writes two lines using two different functions. Let us read this file in the next section.
Reading a File
Given below is the simplest function to read a single character from a file −
The fgetc() function reads a character from the input file referenced by fp. The return value is the character read, or in case of any error, it returns EOF. The following function allows to read a string from a stream −
The functions fgets() reads up to n-1 characters from the input stream referenced by fp. It copies the read string into the buffer buf, appending a null character to terminate the string.
If this function encounters a newline character ‘\n’ or the end of the file EOF before they have read the maximum number of characters, then it returns only the characters read up to that point including the new line character. You can also use int fscanf(FILE *fp, const char *format, . ) function to read strings from a file, but it stops reading after encountering the first space character.
When the above code is compiled and executed, it reads the file created in the previous section and produces the following result −
Let’s see a little more in detail about what happened here. First, fscanf() read just This because after that, it encountered a space, second call is for fgets() which reads the remaining line till it encountered end of line. Finally, the last call fgets() reads the second line completely.
Binary I/O Functions
There are two functions, that can be used for binary input and output −
Both of these functions should be used to read or write blocks of memories — usually arrays or structures.
Create, write, and read a file
Important APIs
Read and write a file using a StorageFile object.
В For a complete sample, see the File access sample.
Prerequisites
Understand async programming for Universal Windows Platform (UWP) apps
You can learn how to write asynchronous apps in C# or Visual Basic, see Call asynchronous APIs in C# or Visual Basic. To learn how to write asynchronous apps in C++/WinRT, see Concurrency and asynchronous operations with C++/WinRT. To learn how to write asynchronous apps in C++/CX, see Asynchronous programming in C++/CX.
Know how to get the file that you want to read from, write to, or both
You can learn how to get a file by using a file picker in Open files and folders with a picker.
Creating a file
Here’s how to create a file in the app’s local folder. If it already exists, we replace it.
Writing to a file
Here’s how to write to a writable file on disk using the StorageFile class. The common first step for each of the ways of writing to a file (unless you’re writing to the file immediately after creating it) is to get the file with StorageFolder.GetFileAsync.
Writing text to a file
Write text to your file by calling the FileIO.WriteTextAsync method.
Writing bytes to a file by using a buffer (2 steps)
First, call CryptographicBuffer.ConvertStringToBinary to get a buffer of the bytes (based on a string) that you want to write to your file.
Then write the bytes from your buffer to your file by calling the FileIO.WriteBufferAsync method.
Writing text to a file by using a stream (4 steps)
First, open the file by calling the StorageFile.OpenAsync method. It returns a stream of the file’s content when the open operation completes.
Next, get an output stream by calling the IRandomAccessStream.GetOutputStreamAt method from the stream . If you’re using C#, then enclose this in a using statement to manage the output stream’s lifetime. If you’re using C++/WinRT, then you can control its lifetime by enclosing it in a block, or setting it to nullptr when you’re done with it.
Now add this code (if you’re using C#, within the existing using statement) to write to the output stream by creating a new DataWriter object and calling the DataWriter.WriteString method.
Lastly, add this code (if you’re using C#, within the inner using statement) to save the text to your file with DataWriter.StoreAsync and close the stream with IOutputStream.FlushAsync.
Best practices for writing to a file
For additional details and best practice guidance, see Best practices for writing to files.
Reading from a file
Here’s how to read from a file on disk using the StorageFile class. The common first step for each of the ways of reading from a file is to get the file with StorageFolder.GetFileAsync.
Reading text from a file
Read text from your file by calling the FileIO.ReadTextAsync method.
Reading text from a file by using a buffer (2 steps)
Then use a DataReader object to read first the length of the buffer and then its contents.
Reading text from a file by using a stream (4 steps)
File. Open Read(String) Метод
Определение
Открывает для чтения существующий файл. Opens an existing file for reading.
Параметры
Файл, открываемый для чтения. The file to be opened for reading.
Возвращаемое значение
Доступный только для чтения FileStream в заданном пути. A read-only FileStream on the specified path.
Исключения
path представляет собой строку нулевой длины, содержащую только пробелы или один или несколько недопустимых символов, заданных методом InvalidPathChars. path is a zero-length string, contains only white space, or contains one or more invalid characters as defined by InvalidPathChars.
path имеет значение null . path is null .
Указанный путь, имя файла или оба значения превышают максимальную длину, заданную в системе. The specified path, file name, or both exceed the system-defined maximum length.
Указан недопустимый путь (например, он ведет на несопоставленный диск). The specified path is invalid, (for example, it is on an unmapped drive).
Параметр path определяет каталог. path specified a directory.
-или- -or- У вызывающего объекта отсутствует необходимое разрешение. The caller does not have the required permission.
Файл, заданный параметром path , не найден. The file specified in path was not found.
Параметр path задан в недопустимом формате. path is in an invalid format.
При открытии файла произошла ошибка ввода-вывода. An I/O error occurred while opening the file.
Примеры
В следующем примере открывается файл для чтения. The following example opens a file for reading.
Комментарии
Этот метод эквивалентен FileStream(String, FileMode, FileAccess, FileShare) перегрузке конструктора со FileMode значением Open , FileAccess значением Read и FileShare значением Read . This method is equivalent to the FileStream(String, FileMode, FileAccess, FileShare) constructor overload with a FileMode value of Open, a FileAccess value of Read and a FileShare value of Read.
path Параметр может указывать сведения относительного или абсолютного пути. The path parameter is permitted to specify relative or absolute path information. Сведения об относительном пути интерпретируется как относительно текущего рабочего каталога. Relative path information is interpreted as relative to the current working directory. Сведения о получении текущего рабочего каталога см. в разделе GetCurrentDirectory . To obtain the current working directory, see GetCurrentDirectory.
Список общих задач ввода-вывода см. в разделе Общие задачи ввода-вывода. For a list of common I/O tasks, see Common I/O Tasks.
C File Handling
In this tutorial, you will learn about file handling in C. You will learn to handle standard I/O in C using fprintf(), fscanf(), fread(), fwrite(), fseek() etc. with the help of examples.
A file is a container in computer storage devices used for storing data.
Why files are needed?
When a program is terminated, the entire data is lost. Storing in a file will preserve your data even if the program terminates.
If you have to enter a large number of data, it will take a lot of time to enter them all. However, if you have a file containing all the data, you can easily access the contents of the file using a few commands in C.
You can easily move your data from one computer to another without any changes.
Types of Files
When dealing with files, there are two types of files you should know about:
1. Text files
Text files are the normal .txt files. You can easily create text files using any simple text editors such as Notepad.
When you open those files, you’ll see all the contents within the file as plain text. You can easily edit or delete the contents.
They take minimum effort to maintain, are easily readable, and provide the least security and takes bigger storage space.
2. Binary files
Binary files are mostly the .bin files in your computer.
Instead of storing data in plain text, they store it in the binary form (0’s and 1’s).
They can hold a higher amount of data, are not readable easily, and provides better security than text files.
File Operations
In C, you can perform four major operations on files, either text or binary:
Creating a new file
Opening an existing file
Closing a file
Reading from and writing information to a file
Working with files
When working with files, you need to declare a pointer of type file. This declaration is needed for communication between the file and the program.
Opening a file — for creation and edit
Opening a file is performed using the fopen() function defined in the stdio.h header file.
The syntax for opening a file in standard I/O is:
Let’s suppose the file newprogram.txt doesn’t exist in the location E:\cprogram . The first function creates a new file named newprogram.txt and opens it for writing as per the mode ‘w’. The writing mode allows you to create and edit (overwrite) the contents of the file.
Now let’s suppose the second binary file oldprogram.bin exists in the location E:\cprogram . The second function opens the existing file for reading in binary mode ‘rb’. The reading mode only allows you to read the file, you cannot write into the file.
Opening Modes in Standard I/O
Mode
Meaning of Mode
During Inexistence of file
r
Open for reading.
If the file does not exist, fopen() returns NULL.
rb
Open for reading in binary mode.
If the file does not exist, fopen() returns NULL.
w
Open for writing.
If the file exists, its contents are overwritten. If the file does not exist, it will be created.
wb
Open for writing in binary mode.
If the file exists, its contents are overwritten. If the file does not exist, it will be created.
a
Open for append. Data is added to the end of the file.
If the file does not exist, it will be created.
ab
Open for append in binary mode. Data is added to the end of the file.
If the file does not exist, it will be created.
r+
Open for both reading and writing.
If the file does not exist, fopen() returns NULL.
rb+
Open for both reading and writing in binary mode.
If the file does not exist, fopen() returns NULL.
w+
Open for both reading and writing.
If the file exists, its contents are overwritten. If the file does not exist, it will be created.
wb+
Open for both reading and writing in binary mode.
If the file exists, its contents are overwritten. If the file does not exist, it will be created.
a+
Open for both reading and appending.
If the file does not exist, it will be created.
ab+
Open for both reading and appending in binary mode.
If the file does not exist, it will be created.
Closing a File
The file (both text and binary) should be closed after reading/writing.
Closing a file is performed using the fclose() function.
Here, fptr is a file pointer associated with the file to be closed.
Reading and writing to a text file
For reading and writing to a text file, we use the functions fprintf() and fscanf().
They are just the file versions of printf() and scanf() . The only difference is that fprint() and fscanf() expects a pointer to the structure FILE.
Example 1: Write to a text file
This program takes a number from the user and stores in the file program.txt .
After you compile and run this program, you can see a text file program.txt created in C drive of your computer. When you open the file, you can see the integer you entered.
Example 2: Read from a text file
This program reads the integer present in the program.txt file and prints it onto the screen.
If you successfully created the file from Example 1, running this program will get you the integer you entered.
Other functions like fgetchar() , fputc() etc. can be used in a similar way.
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 case of binary files.
Writing to a binary file
To write into a binary file, you need to use the fwrite() function. The functions take four arguments:
address of data to be written in the disk
size of data to be written in the disk
number of such type of data
pointer to the file where you want to write.
Example 3: Write to a binary file using fwrite()
In this program, we create a new file program.bin in the C drive.
We declare a structure threeNum with three numbers — n1, n2 and n3 , and define it in the main function as num.
Now, inside the for loop, we store the value into the file using fwrite() .
The first parameter takes the address of num and the second parameter takes the size of the structure threeNum .
Since we’re only inserting one instance of num , the third parameter is 1 . And, the last parameter *fptr points to the file we’re storing the data.
Finally, we close the file.
Reading from a binary file
Function fread() also take 4 arguments similar to the fwrite() function as above.
Example 4: Read from a binary file using fread()
In this program, you read the same file program.bin and loop through the records one by one.
In simple terms, you read one threeNum record of threeNum size from the file pointed by *fptr into the structure num .
You’ll get the same records you inserted in Example 3.
Getting data using fseek()
If you have many records inside a file and need to access a record at a specific position, you need to loop through all the records before it to get the record.
This will waste a lot of memory and operation time. An easier way to get to the required data can be achieved using fseek() .
As the name suggests, fseek() seeks the cursor to the given record in the file.
Syntax of fseek()
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.