编辑器:vs2017
1 // files.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。 2 // 3 4 #include "pch.h" 5 #include<iostream> 6 #include<stdio.h> 7 #include<conio.h> 8 using namespace std; 9 10 #define N 2 11 12 struct Stu 13 { 14 char name[100]; 15 char location[100]; 16 int age; 17 float score; 18 }boy[N],baby[N],*student,*stu1; 19 int main() 20 { 21 ////从键盘输入的数据放入a,从文件读取的数据放入b 22 //int a[N], b[N]; 23 //int i, size = sizeof(int); 24 //FILE *fp; 25 //if ((fp = fopen("D:\\temp\\demo.txt", "rb+")) == NULL) { 26 // printf("Cannot open file, press any key to exit!\n"); 27 // //getch(); 28 // exit(1); 29 //} 30 31 ////从键盘输入数据 并保存到数组a 32 //for (i = 0; i < N; i++) { 33 // scanf("%d", &a[i]); 34 //} 35 ////将数组a的内容写入到文件 36 //fwrite(a, size, N, fp); 37 ////将文件中的位置指针重新定位到文件开头 38 //rewind(fp); 39 ////从文件读取内容并保存到数组b 40 //fread(b, size, N, fp); 41 ////在屏幕上显示数组b的内容 42 //for (i = 0; i < N; i++) { 43 // printf("%d ", b[i]); 44 //} 45 //printf("\n"); 46 //fclose(fp); 47 48 49 50 FILE *fp; 51 int i; 52 student = boy; 53 stu1 = baby; 54 if ((fp = fopen("D:\\temp\\demo.txt", "r+")) == NULL) { 55 printf("Cannot open file, press any key exit!"); 56 //getch(); 57 exit(1); 58 } 59 60 61 ////从键盘读入数据,保存到boy 62 //printf("Input data:\n"); 63 //for (i = 0; i < N; i++, student++) { 64 // scanf("%s %s %d %f", student->name, student->location, &student->age, &student->score); 65 //} 66 //student = boy; 67 ////将boy中的数据写入到文件 68 //for (i = 0; i < N; i++, student++) { 69 // fprintf(fp, "%s %s %d %f\n", student->name, student->location, student->age, student->score); 70 //} 71 72 73 //重置文件指针 74 rewind(fp); 75 //从文件中读取数据,保存到baby 76 for (i = 0; i < N; i++, stu1++) { 77 fscanf(fp, "%s %s %d %f\n", stu1->name, stu1->location, &stu1->age, &stu1->score); 78 } 79 stu1 = baby; 80 //将baby中的数据输出到显示器 81 for (i = 0; i < N; i++, stu1++) { 82 printf("%s %s %d %f\n", stu1->name, stu1->location, stu1->age, stu1->score); 83 } 84 fclose(fp); 85 86 87 88 //system("pause"); 89 return 0; 90 } 91 92 // 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单 93 // 调试程序: F5 或调试 >“开始调试”菜单 94 95 // 入门提示: 96 // 1. 使用解决方案资源管理器窗口添加/管理文件 97 // 2. 使用团队资源管理器窗口连接到源代码管理 98 // 3. 使用输出窗口查看生成输出和其他消息 99 // 4. 使用错误列表窗口查看错误 100 // 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目 101 // 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件