C语言之文件文件概述文件分类文件的打开与关闭文件的读写字符串输入输出数据块的读写函数格式化读写函数顺序读写和随机读写出错的检测文件概述文件分类文件的打开与关闭wt rt at 文本文件 文件的读写文件结束为...

C语言之文件
- 文件概述
- 文件分类
- 文件的打开与关闭
- 文件的读写
- 字符串输入输出
- 数据块的读写函数
- 格式化读写函数
- 顺序读写和随机读写
- 出错的检测
文件概述
文件分类
文件的打开与关闭
wt rt at 文本文件
文件的读写
文件结束为1 文件未结束为0
#include <stdio.h>
#include <stdlib.h>
void main()
{
FILE *pic,*file,*new_file;
char a[20],b[20],c[20];
char ch;
printf("请输入照片的名称: ");
scanf("%s",a);
printf("请输入文件的名称: ");
scanf("%s",b);
printf("请输入要合成文件的名称: ");
scanf("%s",c);
if( !(pic = fopen(a,"rb")) )
{
printf("无法打开照片\n");
}
if( !(file = fopen(b,"rb")) )
{
printf("无法打开文件\n");
}
if( !(new_file = fopen(c,"wb")) )
{
printf("无法打开新文件");
}
while(!(feof(pic)) )
{
ch = fgetc(pic);
fputc(ch,new_file);
}
fclose(pic);
while(!(feof(file)) )
{
ch = fgetc(file);
fputc(ch,new_file);
}
fclose(file);
fclose(new_file);
system("pause");
}
字符串输入输出
数据块的读写函数
#include <stdio.h>
#include <stdlib.h>
#define SIZE 4
struct student
{
char name[10];
int num;
int age;
char addr[15];
}stu[SIZE];
void save()
{
FILE *fp;
int i;
if( !(fp = fopen("student-list","wb")))
{
printf("Cannot open the file!\n");
return;
}
for(i=0;i<SIZE;i++)
{
if( fwrite(&stu[i],sizeof(struct student),1,fp) != 1)
{
printf("File write error!\n");
fclose(fp);
}
}
}
void main()
{
int i;
printf("Please input the student's name,num,age and address: \n");
for(i=0;i<SIZE;i++)
{
scanf("%s %d %d %s",stu[i].name,&stu[i].num,&stu[i].age,&stu[i].addr);
}
save();
}
void load()
{
FILE *fp;
int i;
if( !(fp = fopen("student-list","r")))
{
printf("Cannot open the file\n");
return;
}
for(i=0;i<SIZE;i++)
{
fread(&stu[i],sizeof(struct student),1,fp);
}
fclose(fp);
}
格式化读写函数
顺序读写和随机读写
#include <stdio.h>
#include <stdlib.h>
#define SIZE 4
struct student
{
char name[10];
int num;
int age;
char addr[15];
}boy;
void main()
{
FILE *fp;
int i=1;
if( !(fp = fopen("student-list","r")))
{
printf("Cannot open the file!\n");
return;
}
rewind(fp);
fseek(fp,i*sizeof(struct student),0);
fread(&boy,sizeof(struct student),1,fp);
printf("name\tnumber age addr\n");
printf("%s\t%5d %7d %s\n",boy.name,boy.num,boy.age,boy.addr);
system("pause");
}
出错的检测
织梦狗教程
本文标题为:C语言之文件


基础教程推荐
猜你喜欢
- C++实现ETW进行进程变动监控详解 2023-05-15
- [C语言]二叉搜索树 2023-09-07
- C++实战之二进制数据处理与封装 2023-05-29
- 带你深度走入C语言取整以及4种函数 2022-09-17
- C语言编程C++旋转字符操作串示例详解 2022-11-20
- [c语言-函数]不定量参数 2023-09-08
- C语言实现宾馆管理系统课程设计 2023-03-13
- 全面了解C语言 static 关键字 2023-03-26
- centos 7 vscode cmake 编译c++工程 2023-09-17
- C语言 详解字符串基础 2023-03-27