fread
size_t fread( void *buffer, size_t size, size_t count, FILE *stream );
- 函数返回读取数据的个数。如果调用成功返回实际读取到的项个数(小于或等于count),如果不成功或读到文件末尾返回 0。
buffer
Storage location for data //数据的存储位置
size
Item size in bytes //数据类型的大小(字节)
count
Maximum number of items to be read //数据的个数
stream
Pointer to FILE structure //要读的文件
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE * fp = NULL;
int buffer[10] = {0};
if ((fp = fopen("E:\\ceshi.txt", "r")) == NULL) //文件自己创建
{
printf("cant open the file");
exit(0);
}
while (1)
{
int count = fread(buffer, sizeof(char), sizeof(buffer), fp);
if (count <= 0)
break;
printf("%s\n", buffer);
}
system("pause");
}
fwrite
- 他的功能和
fread
刚好相反,一个从文件中读出来,一个把数据写进去。 - 功能是向指定的文件中写入若干数据块,如成功执行则返回实际写入的数据块数目。该函数以二进制形式对文件进行操作,不局限于文本文件。
size_t fwrite( const void *buffer, size_t size, size_t count, FILE *stream );
buffer
Pointer to data to be written //指向要写的数据
size
Item size in bytes //数据类型的大小
count
Maximum number of items to be written //要写的数据个数
stream
Pointer to FILE structure //要写的文件
- 说明:写入到文件的哪里? 这个与文件的打开模式有关,如果是w+,则是从file pointer指向的地址开始写,替换掉之后的内容,文件的长度可以不变,stream的位置移动count个数;如果是a+,则从文件的末尾开始添加,文件长度加大。
#include <stdio.h>
void main(void)
{
FILE *stream;
char list[30];
int i, numread, numwritten;
/* Open file in text mode: */
if ((stream = fopen("E:\\ceshi.txt", "w+t")) != NULL)
{
for (i = 0; i < 25; i++)
list[i] = (char)('z' - i);
/* Write 25 characters to stream */
numwritten = fwrite(list, sizeof(char), 25, stream);
printf("Wrote %d items\n", numwritten);
fclose(stream);
}
else
printf("Problem opening the file\n");
if ((stream = fopen("E:\\ceshi.txt", "r+t")) != NULL)
{
/* Attempt to read in 25 characters */
numread = fread(list, sizeof(char), 25, stream);
printf("Number of items read = %d\n", numread);
printf("Contents of buffer = %.25s\n", list);
fclose(stream);
}
else
printf("File could not be opened\n");
system("pause");
}
参考MSDN的。有问题还请大家指出。