C语言中文件的读/写结构

先决条件: C中的结构 对于在文件中写入,使用 格式化输出 putc ,但在编写struct的内容时可能会遇到困难。 写入文件 弗雷德 当您想要写入和读取数据块时,使任务更容易。

null
  • 写下: 下面是fwrite函数的声明
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)ptr - This is pointer to array of elements to be writtensize -  This is the size in bytes of each element to be writtennmemb - This is the number of elements, each one with a size of size bytesstream - This is the pointer to a FILE object that specifies an output stream

C

// 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, "Error opened file" );
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 !" );
else
printf ( "error writing file !" );
// close file
fclose (outfile);
return 0;
}


输出:

gcc demowrite.c./a.outcontents to file written successfully!
  • 弗雷德: 下面是fread函数的声明
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream)ptr - This is the pointer to a block of memory with a minimum size of size*nmemb bytes.size - This is the size in bytes of each element to be read.nmemb - This is the number of elements, each one with a size of size bytes.stream - This is the pointer to a FILE object that specifies an input stream.

C

// 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, "Error opening file" );
exit (1);
}
// read file contents till end of file
while ( fread (&input, sizeof ( struct person), 1, infile))
printf ( "id = %d name = %s %s" , input.id,
input.fname, input.lname);
// close file
fclose (infile);
return 0;
}


输出:

gcc demoread.c./a.outid = 1   name = rohan sharmaid = 2   name = mahendra dhoni

本文由 曼迪星 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 写极客。组织 或者把你的文章寄去评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。 如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞8 分享