如:
"B:TEST.DAT"
"C:\\TC\\TEST.DAT"
如果将路径写成"C:\TC\TEST.DAT"是不正确的, 这一点要特别注意。
第二个形式参数表示打开文件的类型。关于文件类型的规定参见下表。
表 文件操作类型
━━━━━━━━━━━━━━━━━━━━━━━━━━━━
字符 含义
────────────────────────────
"r" 打开文字文件只读
"w" 创建文字文件只写
"a" 增补, 如果文件不存在则创建一个
"r+" 打开一个文字文件读/写
"w+" 创建一个文字文件读/写
"a+" 打开或创建一个文件增补
"b" 二进制文件(可以和上面每一项合用)
"t" 文这文件(默认项)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━
如果要打开一个CCDOS子目录中, 文件名为CLIB的二进制文件, 可写成:
fopen("c:\\ccdos\\clib", "rb");
如果成功的打开一个文件, fopen()函数返回文件指针, 否则返回空指针
(NULL)。由此可判断文件打开是否成功。
int fwrite(void *buf, int size, int count, FILE *stream);
它们存放到buf指针所指的缓冲器中。
段写到stream指向的文件中去。返回实际写入的数据项个数count。
若无fclose()//未练习
函数, 则不会向文件中存入所写的内容或写入的文件内容不全。有一个对缓冲区
进行刷新的函数, 即fflush(),
fread,对指定长度的文件数据。读取的长度远小于文件的总长度:
查MSDN,fopen最后一个参数:
tOpen in text (translated) mode.
In this mode, CTRL+Z is interpreted as an end-of-file character on input.
In files opened for reading/writing with "a+", fopen checks for a CTRL+Z at the end of the file and removes it, if possible.
This is done because using fseek and ftell to move within a file that ends with a CTRL+Z can cause fseek to behave improperly near the end of the file.
Also, in text mode, carriage return–linefeed combinations are translated into single linefeeds on input, and linefeed characters are translated to carriage return–linefeed combinations on output.
When a Unicode stream-I/O function operates in text mode (the default), the source or destination stream is assumed to be a sequence of multibyte characters. Therefore, the Unicode stream-input functions convert multibyte characters to wide characters.
For the same reason, the Unicode stream-output functions convert wide characters to multibyte characters.
bOpen in binary (untranslated) mode; translations involving carriage-return and linefeed characters are suppressed.
If t or b is not given in mode, the default translation mode is defined by the global variable _fmode.
If t or b is prefixed to the argument, the function fails and returns NULL.
默认应该是文本模式t,这个时候fread遇到控制字符就不往后读了。
使用binnay mode 这样就能就没有上述问题了,一个简单的例子:
fp=fopen("number.txt","wb");//wb 写入二进制文件count=fwrite(src,sizeof(int),n,fp);
printf("\n%d",count);
fclose(fp);
fp=fopen("number.txt","rb");//读取二进制文件 文本格式读出错
if(fp==NULL)
printf("error");
int *num=(int *)calloc(n,sizeof(int));
count=fread(num+1,sizeof(int),n,fp);