跳至主要內容

fread


fread

函数原型

int fread(addr pt, int size, int n, char fp);

功能

读文件

说明

从句柄为 fp 的文件中读取 n 个字节,存到 pt 所指向的内存区。

返回值:

  • 返回所读的字节数
  • 如遇文件结束或出错返回0

注意:fread 和 fwrite 的参数 size 会被忽略,实际读写的字节数是参数 n。之所以保留 size 是为了与 c 兼容。建议 size 值取1。

示例

char s[] = "www.lavax.net";

void main()
{
    char fp;
    char t[20];

    if ((fp = fopen("/LavaData/tmp.dat", "w+")) == 0)
        printf("创建文件失败!");
    else {
        printf("创建文件成功!");
        fwrite(s, 1, strlen(s) + 1, fp);
        rewind(fp);
        fread(t, 1, strlen(s) + 1, fp);
        printf("\n%s", t);
        fclose(fp);
    }
    getchar();
}