1 #include <iostream> 2 #include <stdio.h> 3 #include <stdlib.h> 4 using namespace std; 5 #define FILENAME "E:\\FUSHI\\test.txt" 6 7 int main() 8 { 9 /* 10 新建文件,并写文件 11 FILE *fp; 12 char f_name[30]; 13 char choise,in_char; 14 15 printf("\n\t请输入要新建的文件名:"); 16 scanf("%s",f_name); 17 fp=fopen(f_name,"w+"); 18 19 in_char=getchar(); 20 while(in_char!=‘*‘) 21 { 22 fputc(in_char,fp); 23 in_char=getchar(); 24 } 25 fclose(fp); 26 //if(fopen("E:\\FUSHI\\text.c","w+")==NULL) 27 */ 28 /* 29 //输入文件名,输出给文件的内容 30 FILE *fp; 31 char out_ch,f_name[30]; 32 printf("\n\t请输入的文件名:"); 33 scanf("%s",f_name); 34 fp=fopen(f_name,"r");//只读 35 if(fp!=NULL) 36 { 37 while((out_ch=fgetc(fp))!=EOF) 38 putchar(out_ch); 39 } 40 else 41 printf("\n\t%s文件不存在。\n",f_name); 42 fclose(fp); 43 */ 44 /* 45 //将文件data1.txt的内容复制到文件data2.txt中 46 FILE *f_in,*f_out; 47 char str[50]; 48 f_out=fopen("E:\\FUSHI\\data1.txt","r"); 49 f_in=fopen("E:\\FUSHI\\data2.txt","w"); 50 while(!feof(f_out)) 51 { 52 fgets(str,30,f_out); 53 fputs(str,f_in); 54 } 55 fclose(f_in); 56 fclose(f_out); 57 */ 58 /* 59 //将10个学生记录输入文件E:\FUSHI\stu1.txt中 60 //并在屏幕上显示 61 FILE *fp; 62 long num;//学号 63 int n,score; 64 char name[20]; 65 fp=fopen("E:\\FUSHI\\stu1.txt","w"); 66 printf("\n请依次输入10个学生的姓名、学号、分数:\n"); 67 for(n=1;n<=10;n++) 68 { 69 scanf("%s%10ld%d",name,&num,&score); 70 fprintf(fp,"%20s%10ld%5d\n",name,num,score); 71 } 72 fclose(fp); 73 74 fp=fopen("E:\\FUSHI\\stu1.txt","r"); 75 for(n=1;n<=10;n++) 76 { 77 fscanf(fp,"%20s%10ld%5d\n",name,&num,&score); 78 printf("%20s%10ld%5d\n",name,num,score); 79 } 80 fclose(fp); 81 */ 82 /* 83 //按数据块读写的函数fread(),fwrite() 84 //将5个学生记录输入文件E:\FUSHI\stu2.txt,然后显示 85 86 typedef struct 87 { 88 char name[20]; 89 long num; 90 int score; 91 }STU; 92 STU stu,a[5]; 93 int i; 94 FILE *fp; 95 fp=fopen("E:\\FUSHI\\stu2.txt","w"); 96 printf("\n请依次输入5个学生的姓名、学号、分数:\n"); 97 for(i=0;i<5;i++) 98 { 99 scanf("%s%ld%d",a[i].name,&a[i].num,&a[i].score); 100 } 101 if(fwrite(a,sizeof(STU),5,fp)!=5) 102 { 103 printf("文件不能写入数据.\n"); 104 exit(1);//异常退出 105 } 106 fclose(fp); 107 108 fp=fopen("E:\\FUSHI\\stu2.txt","r"); 109 for(i=0;i<5;i++) 110 { 111 if(fread(&stu,sizeof(STU),1,fp)==1) 112 { 113 printf("\t%6s%10ld%5d\n",stu.name,stu.num,stu.score); 114 } 115 else 116 { 117 printf("文件不能读取数据.\n"); 118 exit(1); 119 } 120 } 121 fclose(fp); 122 */ 123 //打开并检测是否成功;否则,新建并打开 124 FILE *fp; 125 fp=fopen(FILENAME,"r"); 126 if(fp==NULL) 127 { 128 printf("不能打开文件:%s\n",FILENAME); 129 printf("新建 文件%s\n",FILENAME); 130 fp=fopen(FILENAME,"w"); 131 } 132 else 133 { 134 printf("打开文件成功!\n"); 135 } 136 fclose(fp); 137 138 return 0; 139 }
时间: 2024-11-03 01:26:27