1.打开文件函数
1
2FILE *fopen(*fileName,*mode);
函数的返回值是一个文件指针;
fileName:表示打开文件的名称;
mode:表示打开方式;(同上一篇博客中Matlab中的fopen函数)
注意:matlab中文件名和mode用单引号,C语言中用双引号。
2.读取文件
1
2int fread(void *buffer,unsigned sife,unsigned count,FILE *fp)
参数说明:
buffer:void类型的指针,是读出的数据块存放区域的首地址;
sife:表示一个数据块的字节数;
count:数据块个数;
fp:文件指针,表示要从该文件中读取数据;
注:该函数读取数据的大小为sife*count;
返回值:
正常返回值为count;
异常返回值为0;可由feof()和ferror()来判定出现了什么情况。
3.写入文件
1
2int fwrite(void *buffer,unsigned sife,unsigned count,FILE *fp)
参数说明:
buffer:void类型的指针,是读出的数据块存放区域的首地址;
sife:表示一个数据块的字节数;
count:数据块个数;
fp:文件指针,表示要从该文件中读取数据;
注:该函数读取数据的大小为sife*count;
返回值:
正常返回值为count;
异常返回值为0,表示输出发生错误。
4.文件定位
1
2int fssek(FILE *fp,long offset,int base)
功能说明:
使fp指针指向基于base偏移offset字节的位置。
参数说明:
fp:文件指针
offset:相对于base的字节偏移量。长整型,支持大于64KB的文件。
base:文件指针移动的基准位置,计算文件指针位移的基点。
返回值:
正常返回指针位置;
异常返回-1;
注:
第三个参数origin设定从文件的哪里开始偏移,可能取值为:SEEK_CUR、 SEEK_END 或 SEEK_SET
SEEK_SET: 文件开头
SEEK_CUR: 当前位置
SEEK_END: 文件结尾
其中SEEK_SET,SEEK_CUR和SEEK_END依次为0,1和2.
5.确定文件指针的当前位置
1
2long ftell(FILE *fp);
功能:
获得文件指针当前相对于文件首的偏移字节数;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include<stdio.h>
#include<malloc.h>
int main() {
FILE *fp,*fd;
long length;
float *buffer;
fp = fopen("test.bin", "rb");
if (fp== NULL) {
printf("The file can not be opend.");
return -1;
}
//获取数据长度
fseek(fp,0,SEEK_END);
length = ftell(fp);
//文件指针重新指向
fseek(fp, 0, SEEK_SET);
int state = 0;
buffer = (float *)malloc(length);
state=fread(buffer, sizeof(float), length / sizeof(float), fp);
if (state == 0) {
printf("The data can not be read!");
return -1;
}
fd = fopen("readData.bin","wb");
if (fd == NULL) {
printf("The file can not be opend.");
return -1;
}
state=fwrite(buffer,sizeof(float),length/sizeof(float),fd);
if (state == 0) {
printf("data can not be write!");
}
fclose(fp);
fclose(fd);
free(buffer);
return 0;
}
参考文献
http://www.cnblogs.com/likebeta/archive/2012/06/16/2551780.html
最后
以上就是会撒娇烧鹅最近收集整理的关于C语言中文件操作笔记1.打开文件函数2.读取文件3.写入文件4.文件定位5.确定文件指针的当前位置的全部内容,更多相关C语言中文件操作笔记1.打开文件函数2.读取文件3.写入文件4.文件定位5.确定文件指针内容请搜索靠谱客的其他文章。
发表评论 取消回复