9/20/2017 学<LINUX C编程实战》中
1.打开
File *fopen(const char *path , const char * mode);
fopen实现打开指定的文件FileName,mode指打开的形式,C语言中打开的形式种类如下:
b用于打开二进制文件而非文本文件,这是DOS、Windows下的情况。在Linux中不区分二进制文件和文本文件。
同时注意,标志都是const char * 类型,即都是字符串字面值,需要用到双引号,写成fopen(”1.txt" , r); 是错误的。
由于fopen();的返回值是FILE *类型,所以利用一个相同类型的对象如fp去标识fopen();,即fp标识目标文件。之后对fp的操作即是对目标文件的操作。
2.读写
支持字符串、字符等单位进行读写文件。
int fgetc(FILE *stream);
int fputc(int c, FILE *stream);
char *fgets(char *s, int n, FILE *stream);
int fputs(const char *s, FILE *stream);
int fprintf(FILE *stream, const char *format, ...);
int fscanf (FILE *stream, const char *format, ...);
size_t fread(void *ptr, size_t size, size_t n, FILE *stream);
size_t fwrite (const void *ptr, size_t size, size_t n, FILE *stream);
fread();:实现从流stream中读出n个字段,每个字段长size个字节,并将n个字段放入名为ptr的字符数组中,返回实际读取的字段数。
fwrite();:实现从缓冲区ptr所指的数组中把n个字段写入流stream,每个字段长size个字节,返回实际写入的字段数。
fputs();:实现了把字符串写入流stream中。参数s是一个数组,包含了以'\0'为结尾的字符序列。参数stream是指向FILE对象的指针,该对象标识了要被写入的流。返回值:成功的话返回一个非负值,失败的话返回一个EOF。
注意如果要实现output功能,需要用一个字符串数组存储内容并输出,fputs();是向文件中”ouput“,即写入文件,并非输出文件。
3.定位
int fgetpos(FILE *stream, fpos_t *pos);
int fsetpos(FILE *stream, const fpos_t *pos);
int fseek(FILE *stream, long offset, int whence);
返回值:成功返回0,否则返回非0。
用法如下:
#include <stdio.h> int main ()
{
FILE *fp;
fpos_t position; fp = fopen("file.txt","w+");
fgetpos(fp, &position);
fputs("Hello, World!", fp); fsetpos(fp, &position);
fputs("这将覆盖之前的内容", fp);
fclose(fp); return();
}
创建一个文件file.txt,并以读写的方式打开,首先使用fgetpos();获取文件的初始位置,写入“Hello, World!",然后使用fsetpos();重置为文件头的位置。再写入”这将覆盖之前的内容“,实现内容的覆盖。最终输出”浙江覆盖之前的内容“。
4.关闭
int fclose(FILE *stream);
关闭流stream,刷新缓冲区。参数stream是FILE对象的指针,该对象指定了要被关闭的流。
返回值:成功关闭返回0,失败返回EOF。
例程:
编写一个程序,在当前目录下创建用户可读写文件“hello.txt”,在其中写入“Hello, software weekly”,关闭该文件。再次打开该文件,读取其中的内容并输出在屏幕上。
#include <stdio.h>
#define LENGTH 100 int main()
{
FILE *fp;
char str[LENGTH];
fp = fopen("hello2.txt" , "w+");
if(fp)
{
fputs("Hello,software weekly" , fp);
fclose(fp);
}
fp = fopen("hello2.txt" , "r");
fgets(str , LENGTH , fp);
printf("%s\n" , str);
return ;
}
output:bw98@ubuntu:~/Practice/project3$ ./2
Hello,software weekly