里的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
#include<stdio.h>#include<io.h>
void main()
{
int h
char filename[20] /*定义字符数组存储文件名*/
LOOP:
printf("please input filename:\n")
scanf("%s",&filename) /*输入文件名及路径*/
if(h=creat(filename,0)==-1)
{
printf("\n Error! Cannot vreat!\n") /*错误提示*/
goto LOOP /*跳到LOOP处*/
}
else
{
printf("\nthis file has created!\n") /*成功提示*/
close(h)
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)