使用 C 讀取/寫入檔案中的結構
fwrite() 與 fread() 用於在 C 中寫入檔案。
fwrite() 語法
fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
其中
ptr - 要寫入的元素陣列的指標
size - 要寫入的每個元素的位元組大小
nmemb - 元素數,每個元素的大小為 bytes
stream – 指向指定輸出流的 FILE 物件的指標
fread() 語法
fread(void *ptr, size_t size, size_t nmemb, FILE *stream)
其中
ptr - 指向大小至少為 size*nmemb 位元組的記憶體塊的指標。
size - 要讀取的每個元素的位元組大小。
nmemb - 元素數,每個元素的大小為 bytes。
stream - 指向指定輸入流的 FILE 物件的指標。
演算法
Begin Create a structure Student to declare variables. Open file to write. Check if any error occurs in file opening. Initialize the variables with data. If file open successfully, write struct using write method. Close the file for writing. Open the file to read. Check if any error occurs in file opening. If file open successfully, read the file using read method. Close the file for reading. Check if any error occurs. Print the data. End.
這是一個在 C 中讀/寫結構的示例
示例程式碼
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Student {
int roll_no;
char name[20];
};
int main () {
FILE *of;
of= fopen ("c1.txt", "w");
if (of == NULL) {
fprintf(stderr, "
Error to open the file
");
exit (1);
}
struct Student inp1 = {1, "Ram"};
struct Student inp2 = {2, "Shyam"};
fwrite (&inp1, sizeof(struct Student), 1, of);
fwrite (&inp2, sizeof(struct Student), 1, of);
if(fwrite != 0)
printf("Contents to file written successfully !
");
else
printf("Error writing file !
");
fclose (of);
FILE *inf;
struct Student inp;
inf = fopen ("c1.txt", "r");
if (inf == NULL) {
fprintf(stderr, "
Error to open the file
");
exit (1);
}
while(fread(&inp, sizeof(struct Student), 1, inf))
printf ("roll_no = %d name = %s
", inp.roll_no, inp.name);
fclose (inf);
}輸出
Contents to file written successfully ! roll_no = 1 name = Ram roll_no = 2 name = Shyam
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
安卓
Python
C 程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP