树莓派(8)C语言实验九

实验九 文件IO

知识拓展:
文件IO操作: 对文件系统里的文件进行 打开、创建、读、写、关闭等运用。
C语言下标准文件IO接口(函数):
(1)头文件: stdio.h 输入输出函数: printf 、scanf
(2)相关函数: fopen、fread、fwrite、fclose
2.1 标准文件操作有两套函数:
1.标准C语言下的文件操作接口。fopen系列常用于: 对普通文件的读写。
2.Linux操作系统下的文件操作接口。open系列常用于: 对设备文件进行读写。 (鼠标、键盘、声卡、…)

最常用的四个函数:

#include <stdio.h>
//打开文件
FILE *fopen(const char *path, const char *mode); 
//读文件
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
//写文件
size_t fwrite(const void *ptr, size_t size, size_t nmemb,FILE *stream);
//关闭文件
int fclose(FILE *fp);

写函数基本操作:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
  FILE *file;
  int cnt;
  /*1. 打开文件*/
  file=fopen("D:/123.txt","a+b");
  if(file==NULL)
  {
    printf("文件打开失败!\n");
    return -1;
  }
  /*2. 写数据*/
  cnt=fwrite("1234567890",1,10,file);
  
    /*3. 关闭文件*/
  fclose(file);

  printf("cnt=%d\n",cnt);
  return 0;
}

读文件基本操作:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
  FILE *file;
  int cnt;
  char buff[100];

  /*1. 打开文件*/
  file=fopen("D:/123.txt","rb"); //malloc
  if(file==NULL)
  {
    printf("文件打开失败!\n");
    return -1;
  }
  /*2. 写数据*/
  cnt=fread(buff,1,100,file);
  
    /*3. 关闭文件*/
  fclose(file);  //free 

  buff[cnt]='\0';
  printf("%s\n",buff);
  printf("cnt=%d\n",cnt);
  return 0;
}

1.fileOpenWriet.c 读文件写文件

(1)程序说明:有两个磁盘文件A和B,各存放一行字母,要求把这两个文件中的信息合并并按照字典顺序进行排序,最终写入到一个新文件C中。
(2)实验代码:

a.txt

hello

b.txt

raspberry

fileOpenWrite.c

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

/*
程序说明:有两个磁盘文件A和B,各存放一行字母,
        要求把这两个文件中的信息合并(按字母顺序排列),输出到一个新文件C中。
*/
int main()
{
    FILE*fa,*fb,*fc;
    int i,j,k;
    char str[100],str1[100];
    char tem;
    /*
        利用fopen函数打开a.txt文件,将指针赋给fa

        利用fgets函数将a.txt文件内容赋值给str

        赋值结束后,利用fclose回收fa指针
    */
    /*
        利用fopen函数打开b.txt文件,将指针赋给fb

        利用fgets函数将b.txt文件内容赋值给str1

        赋值结束后,利用fclose回收fb指针
    */
    strcat(str,str1);// 将str1串接到str
    /*
        对str字符串进行字典排序,可以采用冒泡排序法
    */
    for(i=strlen(str)-1;i>1;i--)
        for(j=0;j<i;j++)
    
    /*
        利用fopen函数打开c.txt文件,将指针赋给fc,若c.txt不存在,则fopen命令自动创建c.txt文件

        利用fputs函数将排好序的str,输入到fc指向的c.txt文件中

        结束后,利用fclose回收fb指针
    */
    return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值