C 基础 - 文件输入/输出

 

可以在C语言程序中使用标准I/O对文件进行打开,读写操作。

 

一、什么是文件?

一个文件通常就是磁盘上的一段命名的存储区。 C将文件看成是连续的字节序列,其中每个字节都可以单独的读取。

ANSI C提供了文件的两种视图:

  • 文本视图
  • 二进制视图(程序可以访问文件中每个字节)

 

标准文件:

  • standard input: getchar(), gets, scanf()
  • standard output: putchar(), puts(), printf()
  • standard error output

 

C标准I/O与操作系统底层I/O相比,除了可移植外,还有:

1. 简化处理

2. 输入输出都有缓冲 

 

/*count.c -- 使用标准I/O*/
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    int ch;
    FILE * fp;
    long count = 0;
    
   // 判断输入参数
if(argc != 2) { printf("Usage: %s filename\n", argv[0]); exit(1); }
// 打开文件
if((fp = fopen(argv[1],"r")) == NULL) { printf("Can't open %s\n", argv[1]); exit(1); }

// 读取文件内容,标准输出
while((ch = getc(fp)) != EOF) { putc(ch, stdout); count++; }
// 关闭文件 fclose(fp); printf(
"File %s has %ld characters\n", argv[1], count); return 0; }

 

 

二、标准文件I/O函数

1. 标准打开文件函数

// man 3 fopen

#include <stdio.h>

FILE *
fopen(const char * restrict path, const char * restrict mode);
参数说明:
第一个参数是要打开文件的决对路径与名称
第二个参数是要打开的模式

成功返回文件类型的指针,失败返回-1
FILE
* fdopen(int fildes, const char *mode); FILE * freopen(const char *path, const char *mode, FILE *stream); FILE * fmemopen(void *restrict *buf, size_t size, const char * restrict mode);

 

 

模式字符串 含义
“r” 以读模式打开文件
“w” 以写模式打开文件,把现有文件长度截为0,如果文件不存在,创建一个新文件
“a” 以写模式打开文件,在现有文件未尾添加内容,如果文件不存在,创建一个新文件。
“r+” 以更新模式打开文件(可读可写)
“w+” 以更新模式打开文件
"a+" 以更新模式打开文件
“rb”, “wb”, "ab", "ab+", “a+b”, "wb+", "w+b", “ab+”, “a+b” 以二进制模式打开
“wx”, "wbx", "w+x", "wb+x",  

 

 

 

 

 

 

 

 

 

 

2. getc() 与 putc() 函数

ch = getchar() 从标准输入获取一个字符

ch = getc(fp) 从fp指定的文件中获取一个字符

putc(ch, fpout); 

--------------

int ch;

FILE *fp;

fp = fopen("test.txt", "r");

while((ch = getc(fp)) != EOF) {

  putchar(ch);

}

 

fclose(fp) 函数关闭fp指定的文件。

成功返回0,否则返回EOF。

if(fclose(fp) != 0)

  printf("Error in closing file %s\n", argv[1]);

 

 

 

实际编程题

读取file1.txt 文件中的内容,输出到file2.txt文件中

 

编程题:

磁盘文件file1.txt 与 file2.txt, 各存放一行字母

要求把信息合并(按字母顺序排序), 输出到一个新文件file3.txt中

main()
{
    FILE *fp;
    int i,j,n, ni;
    char c[160], t, ch;

    if(fp = fopen("A", "r") == NULL)
    {
        printf("文件A打开错误");
        exit(0);
    }

    printf("\n 文件A内容为:\n");

    for(i = 0; (ch = fgetc(fp)) != EOF; i ++)
    {
        c[i] = ch;
        putchar(c[i]);
    }

    fclose(fp);

    ni = i;

    if(fp = fopen("B", "r") == NULL)
    {
        printf("文件B打开错误");
        exit(0);
    }

    for(i = 0; (ch = fgetc(fp)) != EOF; i ++)
    {
        c[i] = ch;
        putchar(c[i]);
    }

    for(i = 0; i < n; i++)
        for(j = i+1; j < n; j++)
            if(c[i] > c[j]) {
                t = c[i];
                c[i] = c[j];
                c[j] = t;
            }

    printf("\n C file is: \n");
    fp = fopen("C", "w");
    
    for(i = 0; i < n; i++)
    {
        putc(c[i], fp);
        putchar(c[i]);
    }
    fclose(fp);
    getch();
}

 

posted @ 2016-10-16 18:45  elewei  阅读(293)  评论(0编辑  收藏  举报