文件

来源:互联网 发布:起名字的软件 编辑:程序博客网 时间:2024/04/19 21:04

一般来讲,标准文件操作的4个基本步骤是:

1.文件类型指针的定义

2.打开标准文件

3.标准文件的读或写的操作

4.标准文件的关闭操作


代码示例1:文件的读写

#include<stdio.h>main() {FILE* fp;if((fp=fopen("file1.txt","a"))==NULL) {printf("can not open this file \n");getch();exit(0);}fprintf(fp,"This is a C program! ");fputc('A',fp);fclose(fp);char ch;int i;if((fp=fopen("file1.txt","r"))==NULL) {printf("can not open file \n");exit(1);}while((ch=fgetc(fp))!=EOF)putchar(ch);fclose(fp);system("pause");}


代码示例2:文件的复制

#include<stdio.h>void main(){    FILE* from,* to;    char ch;    char in[10],out[10];    printf("Enter the in file name \n");    scanf("%s",in);    printf("Enter the out file name \n");    scanf("%s",out);    if ((from=fopen(in,"r"))==NULL) {        printf("can not open infile %s\n", in);        exit(0);    }    if ((to=fopen(out,"w"))==NULL) {        printf("can not open outfile %s \n", out);        exit(0);    }    while(!feof(from))        fputc(fgetc(from),to);    fclose(from);    fclose(to);}





原创粉丝点击