c语言保存文件到指定的路径和文件名?

如题所述

fp=fopen(filename,"wb");
里的filename就表示了文件的路径及文件名,所以要把输入的文件名和文件路径拼接起来,计算出这个filename
最好过滤一下别让路径和文件名中有非法字符,比如:\/+<>什么的。
scanf也限制一下长度。
scanf("%19s",filename);
scanf("%19s",path);
参考如下:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *fp;
char ch, filename[20], path[20],buffer[40];
printf("Enter the file name: ");
scanf("%s",filename);
printf("Enter the path: ");
scanf("%s",path);
sprintf(buffer, "%s\\%s", path,filename);
printf("\nto end input ,press Ctrl+Z in newline,then ENTER:\n");
if((fp=fopen(buffer,"wt+"))==NULL)
{
printf("no such path, \nstrike any key exit!");
getch();
exit(1);
}
while ((ch=getchar())!=-1) ch=fputc(ch,fp);
fclose(fp);
printf("==================================\n\n");
printf("file path \"%s\" \nfile name \"%s\":\nand its content:\n",path,filename);
fp=fopen(buffer,"rt");
while ((ch=fgetc(fp))!=-1) putchar(ch);
fclose(fp);
return 0;
温馨提示:答案为网友推荐,仅供参考
相似回答