现在的位置: 首页 > 综合 > 正文

Linux C编程(3) 使用C语言函数读写文件

2018年02月15日 ⁄ 综合 ⁄ 共 1277字 ⁄ 字号 评论关闭

一、逐个字符读文件

1.源代码

#include <stdio.h>

int main()
{
        FILE * fp;
        int i;
        char * path="./test.txt";
        int ch;

        fp = fopen(path, "r");
        if(fp == NULL)
        {
                perror("open error");
                return 1;
        }
        printf("output data in test.txt\n");
        for(i=0; i<5;i++)
        {
                ch = fgetc(fp);
                if(ch == EOF)
                {
                        perror("fgetc error");
                        return 1;
                }
                else
                {
                        printf("%c", (char)ch);
                }
        }

        printf("\nget suceesful\n");
        fclose(fp);
        return 1;
}

      test.txt文件内容

      hi,io

      输出内容为

output data in test.txt
hi,io
get suceesful

2.解释
      fgetc函数声明为

int fgetc(FILE * stream);

      参数stream为FILE结构体的指针,用于指向一个文件,使得该函数从指定的文件中读取一个字节。如果此函数调用成功,则返回读到的字节;如果出错,则返回EOF。EOF在stdio.h中定义的值为-1。

      函数fgetc()调用成功后,返回的是读到的字节,应该为unsigned char 类型,但fget()函数原型中返回值类型是int。原因在于函数调用出错或读到文件末尾是会返回EOF,即-1。在int型的返回值是0xffffffff。如果读到字节oxff,则unsigned char型转换为int型是0x000000ff(即255),只有规定返回值是int型才能把这两种情况区分开。如果规定返回值是unsigned char型,那么当返回值是0xff时则无法区分到底是EOR还是字节oxff。(因为char
c=255; int t=(int)c; t为-1)。【1】
 二、逐个字符写文件

1.源代码

#include <stdio.h>

int main()
{
        FILE * fp;
        int i;
        char * path="./testout.txt";

        fp = fopen(path, "w");
        if(fp == NULL)
        {
                perror("open error");
                return 1;
        }

        char arr[5]={'l','i','n','u','x'};
        for(i=0; i<5;i++)
        {
                if(fputc(arr[i],fp) == EOF)
                {
                        perror("fgetc error");
                        return 1;
                }
        }

        printf("\nputc suceesful\n");
        fclose(fp);
        return 1;
}

      在当前上当下新建文件testout.txt。运行此程序后,文件内容为

      linux

2.解释

      fputc函数声明为

int fputc(int c, FILE * stream);

注意

      刚开始学习linux c,为避免麻烦,最好登录用户为root。

参考文献

【1】《linux c从入门到精通》

抱歉!评论已关闭.