版权声明:本文为博主原创文章,欢迎转载。如有问题,欢迎指正。 https://blog.csdn.net/weixin_42172261/article/details/89399099
/*
文件名:文件路径+文件名主干+文件后缀
文件分为:程序文件和数据文件
根据数据的组织形式,数据文件分为ASCII文件和二进制文件
用fopen函数打开数据文件
FILE *fp=fopen(file_name, methor) fopen("C:\\file_name.dat", "r")
if (fp==NULL){
printf("cannot open this file\n");
exit(0);
}
打开方式
r: 读
w: 写
a: 追加写
向文件读写一个字符
从文件中读取单个字符 fgetc(fp)
从文件中写入单个字符 fputc(ch, fp) 只是单纯写入字符,不写入换行符
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char ch;
FILE *fp;
fp=fopen("D:\\myfile.txt", "w");
if (fp==NULL){
printf("error\n");
exit(-1);
}
while ((ch=getchar())!='#'){
fputc(ch, fp);
}
fclose(fp);
fp=NULL;
return 0;
}
作业
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char ch;
FILE *fp, *fp2;
//作业1 读入字符并写入文件
fp=fopen("C:\\file1.dat", "w");
if (fp==NULL){
printf("error\n");
exit(-1);
}
while ((ch=getchar())!='#'){
fputc(ch, fp);
}
fclose(fp);
fp=NULL;
//作业2 从磁盘文件file1.dat中读出所有的字符,并显示到显示器上
fp=fopen("C:\\file1.dat", "r");
if (fp==NULL){
printf("error\n");
exit(-1);
}
while ((ch=fgetc(fp))!=EOF){
putchar(ch);//putchar()单纯输出字符不加换行
}
fclose(fp);
fp=NULL;
//作业3 将一个磁盘文件中的信息复制到另一个磁盘文件中。
//将file1.dat文件重点的内容复制到file2.dat中
fp=fopen("C:\\file1.dat", "r");
if (fp==NULL){
printf("error\n");
exit(-1);
}
fp2=fopen("C:\\file2.dat", "w");
if (fp2==NULL){
printf("error\n");
exit(-1);
}
while ((ch=fgetc(fp))!=EOF){
fputc(ch, fp2);
}
fclose(fp);
fp=NULL;
fclose(fp2);
fp2=NULL;
return 0;
}