1. 主页
  2. 文档
  3. C语言教程
  4. C语言文件处理
  5. 文件的读/写结构

文件的读/写结构

将字符串或 int 写入文件很容易,但在写入 struct 的内容时可能会遇到困难。当您想要写入和读取数据块时,  fwritefread使任务更容易。

  • fwrite :以下是 fwrite 函数的声明 
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream) 
ptr - 这是指向要写入的元素数组的指针
size - 这是要写入的每个元素的字节大小
nmemb - 这是数字元素,每个元素的大小为 size 字节
stream- 这是指向指定输出流的 FILE 对象的指针
// C program for writing
// struct to file
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// a struct to read and write
struct person
{
int id;
char fname[20];
char lname[20];
};

int main ()
{
FILE *outfile;

// open file for writing
outfile = fopen ("person.dat", "w");
if (outfile == NULL)
{
fprintf(stderr, "\nError opened file\n");
exit (1);
}

struct person input1 = {1, "rohan", "sharma"};
struct person input2 = {2, "mahendra", "dhoni"};

// write struct to file
fwrite (&input1, sizeof(struct person), 1, outfile);
fwrite (&input2, sizeof(struct person), 1, outfile);

if(fwrite != 0)
printf("contents to file written successfully !\n");
else
printf("error writing file !\n");

// close file
fclose (outfile);

return 0;
}

输出: 

gcc demowrite.c
./a.out
contents to file written successfully!
  • fread :以下是 fread 函数的声明 
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream) 
ptr - 这是指向最小大小为 size*nmemb 字节的内存块的指针。
size - 这是要读取的每个元素的字节大小。
nmemb - 这是元素的数量,每个元素的大小为 size 字节。
stream - 这是指向指定输入流的 FILE 对象的指针。
// C program for reading
// struct from a file
#include <stdio.h>
#include <stdlib.h>

// struct person with 3 fields
struct person
{
int id;
char fname[20];
char lname[20];
};

// Driver program
int main ()
{
FILE *infile;
struct person input;

// Open person.dat for reading
infile = fopen ("person.dat", "r");
if (infile == NULL)
{
fprintf(stderr, "\nError opening file\n");
exit (1);
}

// read file contents till end of file
while(fread(&input, sizeof(struct person), 1, infile))
printf ("id = %d name = %s %s\n", input.id,
input.fname, input.lname);

// close file
fclose (infile);

return 0;
}

输出: 

gcc demoread.c
./a.out
id = 1   name = rohan sharma
id = 2   name = mahendra dhoni
这篇文章对您有用吗?