标准IO
demo
这段程序会打开代码所在目录的上一级目录的名为 a.txt 的文件,将里面的数据读取出来然后打印在命令行,同时将数据存储在与 a.txt 同级文件夹下的 b.txt 文件里面。
#include <stdio.h>
int main()
{
// fopen 打开文件 如果没打开返回空指针。
FILE *file = fopen("../a.txt", "r+");
FILE *file_b = fopen("../b.txt", "a+");
if (file == NULL || file_b == NULL)
{
// 标准错误输出
fprintf(stderr, "文件没打开");
return -1;
}
int ch;
// 文件结尾EFO
while ((ch = getc(file)) != EOF)
{
putchar(ch);
putc(ch, file_b);
}
// 关闭文件 成功关闭返回0,否则返回EFO`
int result = fclose(file);
fclose(file_b);
if (result != 0)
{
fprintf(stderr, "文件没有成功关闭");
}
return 0;
}
常用API详解
fopen("fileNmae", "mode")
extern FILE *fopen (const char *__restrict __filename, const char *__restrict __modes) __wur; /* Open a file, replacing an existing stream with it. This function is a possible cancellation point and therefore not marked with __THROW. */
- 第一个参数是打开文件的文件名
- 第二个参数是打开文件的模式
- 返回值:
- 成功打开文件返回文件指针
- 失败打开返回空指针
getc()
&putc()
extern int getc (FILE *__stream); /* Read a character from stdin. This function is a possible cancellation point and therefore not marked with __THROW. */ extern int putc (int __c, FILE *__stream); /* Write a character to stdout. This function is a possible cancellation point and therefore not marked with __THROW. */
getc()
函数读取到文件结尾的时候会返回EOF
。以此为判断目标,来看文件是否读取结束。
共有条评论 网友评论