文件操作之按照字符读写文件

对学习C语言而言,文件操作属于横向学习,而之前的指针属于纵向学习。所谓横向学习,就是快速掌握API,了解使用就行,纵向学习则不同,纵向学习需要深入地理解原理。但是在linux系统编程的学习中,文件操作属于纵向学习,因为在Linux设计哲学中是一切皆文件的思想。

第一个API函数,fopen

第二个API函数,fclose

在打开文件之后,不再操作文件了,都需要将文件流关闭。

eg:先实现创建并写入文件数据:

#include <stdio.h>
#include<stdlib.h>
int main()
{
    FILE *fp;
    const char *filename="F:/mytest/mytext.txt";
    fp=fopen(filename,"w");
    char *text="i am a filetest!\r\n";
    if(fp==NULL)
    {
        printf("open file failure!");
        exit(1);
    }
    else
    {
        while(*text!='\0')
         fputc(*text++,fp);
    }
    fclose(fp);
   return(0);
}

 读出文件在终端显示:

#include <stdio.h>
#include<stdlib.h>
int main()
{
    FILE *fp;
    const char *filename="F:/mytest/mytext.txt";
    fp=fopen(filename,"r+");
    char *text="i am a filetest!\r\n";
    if(fp==NULL)
    {
        printf("open file failure!");
        exit(1);
    }

        int ch=getc(fp);
        while(ch!=EOF)
        {
             printf("%c",ch);
            ch=getc(fp);
        }
    
    fclose(fp);
   return(0);
}

读写综合:

#include <stdio.h>
#include<stdlib.h>
int main()
{
    FILE *fp;
    const char *filename="F:/mytest/mytext.txt";
    fp=fopen(filename,"w+");
    char *text="i am a filetest!\r\n";
    if(fp==NULL)
    {
        printf("open file failure!");
        exit(1);
    }
    else
    {
        while(*text!='\0')
         fputc(*text++,fp);
    }
    fclose(fp);
    fp=fopen(filename,"r+");
        if(fp==NULL)
    {
        printf("open file failure!");
        exit(1);
    }
        int ch=getc(fp);
        while(ch!=EOF)
        {
             printf("%c",ch);
            ch=getc(fp);
        }
    
    fclose(fp);
   return(0);
}

注意,写入文件之后,需要关闭文件流,再重新打开读入终端。在接fgetc的时候,我用的int ch,因为C语言中,char就是int的数值,可以通过sizeof(‘a’)的结果看出,一个字符的sizeof大小为int 的大小。c++中则不再是这样。注意在指定文件路径的时候,请使用'/'符号而不是'\'符号,因为左斜杠在Windows和Linux上通用,而且更好用,Windows再设计的时候什么都和Linux反着来,但这里Windows采用'\'表示路径实为一个纰漏,因为这会和转义字符混淆,所以使用'\'的时候,上面的路径要改为F:\\mytest\\mytext.txt 要表示一个'\',在字符串中必须在'\'前再加一个'\'。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值