先判断路径是否存在,不存在,则创建 #include <stdio.h> #include <stdlib.h> #include <iostream.h> #include <io.h> #include <windows.h> #include <string.h> struct student { int a; }stu[100]; int main(void) { int i; for(i = 0;i <= 99; i++) stu[i].a = i; FILE *fp; char filepath[50], filename[10]; cout < <"enter the filepath : "; cin>>filepath; /* 如:c://aaa// */ if(0 != access(filepath, 0)) //判断路径是否存在 { cout < <"the filepath is not exit!" < <endl; cout < <"Do you want system auto create?(y/n)"; char c; cin>>c; if((c == 'y')||(c == 'Y')) { CreateDirectory(filepath, 0); /*创建路径,如:c://aaa//*/ } else { exit(0); } } cout < <"enter the filename:"; //输入要创建的文件名 cin>>filename; strcat(filepath, filename); cout < <endl < <"the path is :" < <filepath < <endl; cout < <endl; if(NULL == (fp = fopen(filepath, "w"))) { printf("NO"); exit(0); } for(i = 0; i <= 99; i++) { fprintf(fp, "%d /n", stu[i].a); //将stu[i].a的数据写入文件 } printf("Yes!/n"); fclose(fp); return 0; }