标准IO库fgets和fputs对一个文本文件的读写操作

一 前言

本篇主要讲解如何使用缓冲IO对文件进行读写操作,使用fgets函数和fputs函数。

二 fgets

  1. fgets的原型
    char *fgets (char *buffer,int buffer_size,FILE *stream);
  2. 返回值
    fgets返回它的第一个参数,这个返回值用来记录读取的内容。
    如果返回值是NULL,则表示当前已经到了文件尾
  3. 读取规则
    1. 直到读取一个换行符为止
    2. 设定一行的最大长度MAX_LINE_LENGTH

三 fputs

  1. fputs的原型
    int fputs(char const *buffer,FILE *stream) ;
  2. 返回值
    fputs写入错误时,返回EOF,写入成功返回一个非负数。
    fputs() return a nonnegative number on success, or EOF on error.

四 文本文件的读写行

通过一个案例了解这两个函数的用法
读取文件的一行,并将内容写到新文件内

/***********************************************
					1.txt
***********************************************/
123
456
789

IOFile.h

#ifndef _IOFile_H
#define _IOFile_H
//读取一行
int file_read_line(char *path,char *message);
//写入一行
int file_write_line(char *path,char *message);
//读取一个文件
int  file_read(char *path,char *message);
#endif

Main.c代码

#include <stdio.h>

#include "IOFile.h"

#define MAX_LINE_LENGTH 1024

int main () {
	char message[MAX_LINE_LENGTH];
	char *path_1 = "./1.txt";//字符串指针只可读
	char *path_2="./2.txt";
	file_read_line(path_1,message);
	file_write_line(path_2,message);
	file_read_line(path_1,message);
	file_write_line(path_2,message);
	return 0;
}

IOFile.c

#include <stdio.h>
#include "IOFile.h"
#include <string.h>
int  file_read_line(char *path,char *message){

	if(path ==NULL) return 1;

	FILE *file  = fopen(path,"r");
	if(file == NULL )  {
		perror("IoRead open file:");
		return 1;	
	}
	
	if( fgets(message,1024,file) ==NULL ) {
		printf("这是个空文件");
	}else{
		printf("%s",message);
	}
	
	if(fclose(file) !=0){
		perror("IoRead close file:");
		return 1;
	}

	return 0;

}

int file_write_line(char *path,char *message){

	if(path ==NULL) return 1;


	FILE *file  = fopen(path,"w");
	if(file == NULL )  {
		perror("IoWrite open file:");
		return 1;	
	}
	int num=0;
	if(fputs(message,file)==EOF){
		perror("IoWrite write:");
		return 1;
	}
	
	
	if(fclose(file) !=0){
		perror("IoWrite close file:");
		return 1;
	}

	return 0;
}

运行
gcc Main.c IOFile.h IOFile.c
./a.out
123
123

五 读取一个文本文件

Main.c

#include <stdio.h>

#include "IOFile.h"

#define MAX_LINE_LENGTH 1024

int main () {
	char message[MAX_LINE_LENGTH];
	char *path_1 = "./1.txt";//不可写
	file_read(path_1,message);
	return 0;
}

IOfile.c

int  file_read(char *path,char *message) {

	if(path ==NULL) return 1;

	FILE *file  = fopen(path,"r");
	if(file == NULL )  {
		perror("IoRead open file:");
		return 1;	
	}
	
	while( fgets(message,1024,file) !=NULL ) {
		
		printf("%s",message);
	}
	printf("\n");
	if(fclose(file) !=0){
		perror("IoRead close file:");
		return 1;
	}

	return 0;	
}

运行 结果
123
456
789

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值