C : 文件 I/O (2)

一、字符的读写(fgetc() fputc())
1、在运行窗口输入字符,回车确认,在文件中写入这些字符

//字符读写
#include<stdio.h>
#include<conio.h>  //getchar()
#include<process.h>
int main() {
	FILE *P;
	char ch;
	P=fopen("test.txt","w");
	if(P==NULL){
		printf("文件打开失败");
		exit(0); 
	}
	while((ch=getchar()) != '\n')  //getchar():从键盘上读取一个字符,需要回车确认 
		fputc(ch,P);               //将键盘上的数字写入P所指向的文件 
	fclose(P);
	return 0; 
}

2、在源文件目录下,建立一个txt文件,并将其中的字符读出,显示到屏幕上

#include<stdio.h>
#include<conio.h>
#include<process.h>
main(){
	FILE *P;
	char ch;
	P=fopen("test.txt","r");
	if(P==NULL){
		printf("打开文件失败");
		exit(0); 
	}
	while((ch=fgetc(P))!=EOF){  //读取到文件末尾则返回符号常量EOF
		putchar(ch); 
	}
	fclose(P);
}

二、字符串读写(fgets() fputs())
函数原型:
char * fgets(char *str,int n,FILE *P)
将P所指向的文件中,读取n-1个字符,存放到str指向的内存中,遇到\n,EOF,或者n-1个字符时返回这段字符串的首地址

char* fputs(char *str,FILE *P)
将str中的字符写入P指向的文件中

#include<stdio.h>
#include<conio.h>
#include<process.h>
#define N 30 
main(){
	FILE *P;
	char ch[N];  //c中定义字符串 
	P=fopen("test.txt","r");
	if(P==NULL){
		printf("打开文件失败");
		exit(0); 
	}
	while(!feof(P)){
		fgets(ch,27,P);  //读取26个字符 
		fputs(ch,stdout);  //stdout:标准输出流 (FILE *stdout),即在显示器上显示出来 
	}
	fclose(P);
}

三、数据快的读写

fwrite(*buf,size,n,*P)
:将buf中的n个size字节的变量写入P指向的文件中

fread(*buf,size,n,*P)
:将P指向的文件中读取n个size字节的变量,存放到buf指向的内存中

//结构体变量与数组名不同,数组名即为地址名,而结构体变量是标量,取地址:&cbook 
#include<stdio.h>
#include<conio.h>
#define N 20
typedef struct{
	char name[5];
	float grade;
}STD;
int main(){
	STD stu,stud[N];
	FILE *P;
	P=fopen("data","wb"); // 写二进制文件data
	for(int i=0;i<3;i++){
		printf("输入姓名:"); 
		scanf("%s",stu.name);
		printf("输入成绩:"); 
		scanf("%f",&stu.grade);
		fwrite(&stu,sizeof(STD),1,P);  //结构体变量与数组名不同,数组名即为地址名,而结构体变量是标量,取地址:&stu 
	};
	fclose(P); //记得先关闭
	printf("已建立data二进制文件\n");
	P=fopen("data","rb");
	fread(stud,sizeof(STD),3,P); //读取文件并将数据存放到 结构体数组:stud数组中。stud为该数组首地址
	fclose(P); //记得关闭
	for(int x=0;x<3;x++){
		printf("%5s %5f\n",stud[x].name,stud[x].grade); 
	}
	return 0;	 
} 

运行结果如图四、文件的随机访问
FILE中有文件位置指针,指向当前的读取位置
可以通过一些函数对指针位置进行改变,以选择性的读取内容
fseek(fp,offset,whence)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值