C读写文件操作总结

来源:互联网 发布:美洽软件下载 编辑:程序博客网 时间:2024/05/01 00:20
FILE *fopen(    const char *filename,   const char *mode );

一、对已经存在的文件进行读写

mode:
“r”—— Opens for reading.
“r+”—- Opens for both reading and writing.
若文件不存在,fopen返回NULL。

1.打开文件

FILE *fp = fopen("d:\\1234.txt", "r+");if (fp == NULL) ...;  // 打开失败,最有可能是文件不存在

2.定位文件指针

int fseek(    FILE *stream,   long offset,   int origin );

origin:
SEEK_CUR—— Current position of file pointer.
SEEK_END —— End of file.
SEEK_SET —— Beginning of file.

// 定位到文件结尾fseek(fp, 0, SEEK_END);  // 定位到文件开头fseek(fp, 0, SEEK_SET); // 定位到文件开头rewind(fp);

3.获取文件大小

fseek(fp, 0, SEEK_END);long fileSize = ftell(fp);

4.读文件

4.1 读取数据块

size_t fread(    void *buffer,   size_t size,   size_t count,   FILE *stream );

返回实际读取的元素个数。
eg:

char list[11] = { 0 };fread(list, sizeof(char), 10, fp);

4.2 读取字符及字符串

(1)读取单个字符

int fgetc(    FILE *stream );

eg:

char ch = fgetc(fp);

(2)读取字符串

char *fgets(    char *str,   int n,   FILE *stream );

eg:

char list[10] = { 0 };fgets(list, sizeof(list), fp);fgets(list, 10, fp);

Note:
The fgets function reads a string from the input stream argument and stores it in str.
fgets reads characters from the current stream position to and including the first newline character,
to the end of the stream, or until the number of characters read is equal to n – 1, whichever comes first.
The result stored in str is appended with a null character. The newline character, if read, is included in the string.
最多只会从文件中读取n-1个字符,并且会自动在str末尾加上null character.
如果在这之前有读到newline character,则也将结束.

4.3 格式化读取

int fscanf(    FILE *stream,   const char *format [,      argument ]... );

eg:

fseek(fp, 0, SEEK_SET);int a, b, c;fscanf(fp, "%d %d %d", &a, &b, &c);

5.写文件

5.1 写入数据块

size_t fwrite(   const void *buffer,   size_t size,   size_t count,   FILE *stream );

eg:

fseek(fp, 0, SEEK_END);char list[11] = "1234567890";fwrite(list, sizeof(char), strlen(list), fp);

5.2 写入字符及字符串

(1)写入单个字符

int fputc(   int c,   FILE *stream );

eg:

fseek(fp, 0, SEEK_END);fputc('a', fp);

(2)写入字符串

int fputs(    const char *str,   FILE *stream );

eg:

fputs("123", fp);

5.3 格式化写入

int fprintf(    FILE *stream,   const char *format [,      argument ]...);

eg:

fseek(fp, 0, SEEK_END);int a = 10, b=56;fprintf(fp, "%d+%d=%d", a, b, a+b);

二、新建文件进行读写

mode:
“w”——- Opens an empty file for writing. If the given file exists, its contents are destroyed.
“w+”—— Opens an empty file for both reading and writing. If the given file exists, its contents are destroyed.

Note:如果文件已经存在,则其内容会被清除。如果文件不存在,则会创建。
其余操作类同(一)

三、添加文件内容

mode:
“a”—— Opens for writing at the end of file(appending); creates the file first if it does not exist.
“a+”—– Opens for reading and appending; creates the file first if it does not exist.

Note:
When a file is opened with the “a” or “a+” access type, all write operations occur at the end of the file.
The file pointer can be repositioned using fseek or rewind,
but is always moved back to the end of the file before any write operation is carried out.
Thus, existing data cannot be overwritten.

其余操作类同(一)

示例

1.一次性读取整个文件

FILE* fp = fopen("D:\\123.txt", "r");if (NULL == fp){    return 0;}fseek(fp, 0, SEEK_END);long fileSize = ftell(fp);fseek(fp, 0, SEEK_SET);char* contents = new char[fileSize + 1];memset(contents, 0, sizeof(char) * (fileSize + 1));fread(contents, sizeof(char), fileSize, fp);......delete[] contents;fclose(fp);

2.逐行读取文本文件

常见问题

如何判断文件指针已到结尾

前提:fp为有效的文件指针

bool IsFileEnd(FILE *fp){    fgetc(fp);    if (feof(fp))    {        return true;    }    else    {        fseek(fp, -1, SEEK_CUR);        return false;    }}

文本方式操作文件与二进制方式操作文件的区别

(1)用二进制模式打开一个文件的时候,文件本身的内容和你编写程序时用函数读到的内容完全相同(或者说和磁盘上的内容完全相同).

(2)但是如果用了文本模式,那么操作系统在将文件内容传给上层程序(库函数,或者是你的程序)时,或者上层程序通过操作系统向文件写入内容时,
操作系统都会预先进行一层预处理(或者说转义),具体过程依赖于操作系统的实现.在Windows+VC下,最常见就是将回车符\r\n解释成\n(读出时),
将\n解释成\r\n(写入时).而在Linux下没有这层转换,这也是Windows和Linux文本文件不通用的原因.

在Windows下,你新建一文本文件123.txt,编码为ANSI.打开文件,敲入Enter换行然后再保存,查看文件大小为2个位元.
实际文件内容为0d 0a,即两个位元:\r和\n

Note:在文本模式下最好少用fseek.

FILE *fp = fopen("d:\\1234.txt", "r+");

默认以文本方式打开文件,若要以二进制方式打开文件

FILE *fp = fopen("d:\\1234.txt", "rb+");
0 0
原创粉丝点击