C Введення / виведення файлів: відкриття, читання, запис та закриття файлу

У цьому посібнику ви дізнаєтеся про обробку файлів у C. Ви навчитесь обробляти стандартні вводи-виводи в C за допомогою fprintf (), fscanf (), fread (), fwrite (), fseek () тощо за допомогою приклади.

Файл - це контейнер у запам'ятовуючих пристроях комп'ютера, який використовується для зберігання даних.

Навіщо потрібні файли?

  • Коли програма припиняється, втрачаються всі дані. Зберігання у файлі збереже ваші дані, навіть якщо програма завершується.
  • Якщо вам доведеться ввести велику кількість даних, для їх введення знадобиться багато часу.
    Однак якщо у вас є файл, що містить усі дані, ви можете легко отримати доступ до вмісту файлу, використовуючи кілька команд у C.
  • Ви можете легко перенести дані з одного комп’ютера на інший без будь-яких змін.

Типи файлів

Коли ви маєте справу з файлами, вам слід знати два типи файлів:

  1. Текстові файли
  2. Бінарні файли

1. Текстові файли

Текстові файли - це звичайні файли .txt . Ви можете легко створювати текстові файли за допомогою будь-яких простих текстових редакторів, таких як Блокнот.

Відкривши ці файли, ви побачите весь вміст у файлі як звичайний текст. Ви можете легко редагувати або видаляти вміст.

Вони докладають мінімальних зусиль для обслуговування, легко читаються, забезпечують найменший рівень безпеки та займають більше місця для зберігання.

2. Бінарні файли

Бінарні файли - це здебільшого файли .bin на вашому комп'ютері.

Замість того, щоб зберігати дані у простому тексті, вони зберігають їх у двійковій формі (0 та 1).

Вони можуть містити більший обсяг даних, їх не легко прочитати та забезпечує кращий захист, ніж текстові файли.

Файлові операції

У C ви можете виконати чотири основні операції з файлами, як текстовими, так і двійковими:

  1. Створення нового файлу
  2. Відкриття існуючого файлу
  3. Закриття файлу
  4. Читання та запис інформації у файл

Робота з файлами

Під час роботи з файлами потрібно оголосити покажчик типу file. Ця декларація необхідна для зв'язку між файлом та програмою.

 FILE *fptr;

Відкриття файлу - для створення та редагування

Відкриття файлу виконується за допомогою fopen()функції, визначеної у stdio.hфайлі заголовка.

Синтаксис для відкриття файлу у стандартному введенні / виведенні:

 ptr = fopen("fileopen","mode"); 

Наприклад,

 fopen("E:\cprogram\newprogram.txt","w"); fopen("E:\cprogram\oldprogram.bin","rb");
  • Припустимо, що файл newprogram.txtне існує в цьому місці E:cprogram. Перша функція створює новий файл з іменем newprogram.txtі відкриває його для запису відповідно до режиму 'w' .
    Режим запису дозволяє створювати та редагувати (перезаписувати) вміст файлу.
  • Тепер припустимо, що другий двійковий файл oldprogram.binіснує у цьому місці E:cprogram. Друга функція відкриває наявний файл для читання у двійковому режимі 'rb' .
    Режим читання дозволяє лише прочитати файл, ви не можете записати у файл.
Режими відкриття в стандартному вводі-виведенні
Режим Значення режиму Під час Неіснування файлу
r Відкритий для читання. Якщо файл не існує, fopen()повертає NULL.
rb Відкритий для читання в двійковому режимі. Якщо файл не існує, fopen()повертає NULL.
w Відкритий для написання. Якщо файл існує, його вміст замінюється.
Якщо файл не існує, він буде створений.
wb Відкритий для запису в двійковому режимі. Якщо файл існує, його вміст замінюється.
Якщо файл не існує, він буде створений.
a Відкрити для додавання.
Дані додаються в кінець файлу.
Якщо файл не існує, він буде створений.
ab Відкрити для додавання у двійковому режимі.
Дані додаються в кінець файлу.
Якщо файл не існує, він буде створений.
r+ Відкритий як для читання, так і для письма. Якщо файл не існує, fopen()повертає NULL.
rb+ Відкритий як для читання, так і для запису в двійковому режимі. Якщо файл не існує, fopen()повертає NULL.
w+ Відкритий як для читання, так і для письма. Якщо файл існує, його вміст замінюється.
Якщо файл не існує, він буде створений.
wb+ Відкритий як для читання, так і для запису в двійковому режимі. Якщо файл існує, його вміст замінюється.
Якщо файл не існує, він буде створений.
a+ Відкритий як для читання, так і для додавання. Якщо файл не існує, він буде створений.
ab+ Відкритий для читання та додавання у двійковому режимі. Якщо файл не існує, він буде створений.

Закриття файлу

Файл (як текстовий, так і двійковий) слід закрити після читання / запису.

Закриття файлу виконується за допомогою fclose()функції.

 fclose(fptr);

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

 #include #include int main() ( int num; FILE *fptr; // use appropriate location if you are using MacOS or Linux fptr = fopen("C:\program.txt","w"); if(fptr == NULL) ( printf("Error!"); exit(1); ) printf("Enter num: "); scanf("%d",&num); fprintf(fptr,"%d",num); fclose(fptr); return 0; ) 

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

 #include #include int main() ( int num; FILE *fptr; if ((fptr = fopen("C:\program.txt","r")) == NULL)( printf("Error! opening file"); // Program exits if the file pointer returns NULL. exit(1); ) fscanf(fptr,"%d", &num); printf("Value of n=%d", num); fclose(fptr); return 0; ) 

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:

  1. address of data to be written in the disk
  2. size of data to be written in the disk
  3. number of such type of data
  4. pointer to the file where you want to write.
 fwrite(addressData, sizeData, numbersData, pointerToFile);

Example 3: Write to a binary file using fwrite()

 #include #include struct threeNum ( int n1, n2, n3; ); int main() ( int n; struct threeNum num; FILE *fptr; if ((fptr = fopen("C:\program.bin","wb")) == NULL)( printf("Error! opening file"); // Program exits if the file pointer returns NULL. exit(1); ) for(n = 1; n < 5; ++n) ( num.n1 = n; num.n2 = 5*n; num.n3 = 5*n + 1; fwrite(&num, sizeof(struct threeNum), 1, fptr); ) fclose(fptr); return 0; ) 

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.

 fread(addressData, sizeData, numbersData, pointerToFile);

Example 4: Read from a binary file using fread()

 #include #include struct threeNum ( int n1, n2, n3; ); int main() ( int n; struct threeNum num; FILE *fptr; if ((fptr = fopen("C:\program.bin","rb")) == NULL)( printf("Error! opening file"); // Program exits if the file pointer returns NULL. exit(1); ) for(n = 1; n < 5; ++n) ( fread(&num, sizeof(struct threeNum), 1, fptr); printf("n1: %d n2: %d n3: %d", num.n1, num.n2, num.n3); ) fclose(fptr); return 0; ) 

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()

 fseek(FILE * stream, long int offset, int whence);

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.

Різне звідки у fseek ()
Звідки Значення
SEEK_SET Починає зміщення з початку файлу.
SEEK_END Починає зміщення з кінця файлу.
SEEK_CUR Починає зміщення від поточного розташування курсору у файлі.

Приклад 5: fseek ()

 #include #include struct threeNum ( int n1, n2, n3; ); int main() ( int n; struct threeNum num; FILE *fptr; if ((fptr = fopen("C:\program.bin","rb")) == NULL)( printf("Error! opening file"); // Program exits if the file pointer returns NULL. exit(1); ) // Moves the cursor to the end of the file fseek(fptr, -sizeof(struct threeNum), SEEK_END); for(n = 1; n < 5; ++n) ( fread(&num, sizeof(struct threeNum), 1, fptr); printf("n1: %d n2: %d n3: %d", num.n1, num.n2, num.n3); fseek(fptr, -2*sizeof(struct threeNum), SEEK_CUR); ) fclose(fptr); return 0; ) 

Ця програма почне читати записи з файлу program.binу зворотному порядку (від останнього до першого) та роздрукує їх.

Цікаві статті...