初版:2015-03-17 最終更新:2015-03-17 By CaptainOU
1. 概述
①当程序启动时,下面的文件已经被打开。stdin(标准入力)、stdout(标准输出)、stderr(标准错误输出)
②printf()函数往stdout里面写入数据。printf("hello world\n");和fprintf(stdout, "hello world\n");是相同的。
③scanf( )函数是从stdin中读取数据。
2. 文件操作:

3. 打开文件
C语言中,通过fopen()函数来打开文件时,在内存上就会生成FILE类型的结构体。fopen()函数会返回指向FILE结构体的指针。※stdio.h头文件中,如果有"#define FOPEN_MAX 15"的描述、那么一次打开文件的最大个数为15。
①FILE结构体简介:
点击(此处)折叠或打开
-
typedef struct {
-
/* 打开文件的访问模式(r, w, r/w) */
-
char mode;
-
/* 读取写入的位置(从开始位置开始的bit数) */
-
char *ptr;
-
/* 从ptr指示的读取写入位置开始到文件末尾的bit数 */
-
int rcount;
-
/* 从ptr指示的读取写入位置开始到文件末尾的bit数 */
-
int wcount;
-
/* 文件访问用缓存的开始位置 */
-
char *base;
-
/* 文件访问用缓存的大小 */
-
unsigned bufsiz;
-
/* 文件描述符(标准入力、标准输出、标准错误输出的番号) */
-
int fd;
-
char smallbuf[1];
- } FILE;
例:从文件的开头开始取10个文字,取3次。
点击(此处)折叠或打开
-
#include <stdio.h>
-
#include <stdlib.h>
-
int main(int argc, char *argv[]) {
-
int i, j, c;
-
/* NULL定义在stdio.h文件中、#define NULL ((void *)0)。 */
-
FILE *fp = NULL;
-
-
if(!(fp = fopen("test.txt", "r"))) {
-
fprintf(stderr, "Can not open the file.\n);
-
/* void exit(int 状态值); 定义在stdlib.h文件中 */
-
/* 状态值表示终了状态,定义值如下: */
-
/* EXIT_SUCCESS: 0 */
-
/* EXIT_FAILURE: 1 */
-
exit(EXIT_FAILURE);
-
}
-
-
for (i=0; i<3; i++) {
-
for (j=0; j<10; j++) {
-
c = fgetc(fp);
-
putchar(c);
-
putchar('\n');
-
}
-
-
fp->_ptr -= 10;
-
}
-
fclose(fp);
-
/* system函数可以调用DOS系统命令 */
-
system("pause");
return 0;
}
②fopen()函数简介:
函数原型:FILE *fopen(const char *filename, const char *mode);
头文件:#include
参数: filename表示文件的名称,mode表示打开文件的模式。
打开文件模式mode主要有以下几种:
r: 读取模式返回值: 成功则返回文件指针,失败则返回NULL
w: 写入模式(如果文件以及存在则覆盖集成内容,文件不存在则新生成文件)
a: 追加写入模式(从文件的最后开始写入)。
r+, w+, a+: 更新模式(这种模式下既可以写入也可以读取)。
例:
点击(此处)折叠或打开
-
if(!(fp = fopen("test.txt", "r"))) {
-
fprintf(stderr, "Can not open the file.\n");
-
exit(EXIT_FAILURE);
- }