⑴ 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;
⑵ 在C语言读文件时,如何说明是当前目录
这个如果是在c语言中是根据你读文件那个函数里定义的,如果那里你用绝对地址那你放那都可以,如果用相对地址就放到你c编译器的根目录下面,或者子目录,但是子目录需要在里面指出
⑶ 求c语言读取写入文本文件的函数实现
#include<stdio.h>
#include<string.h>//strlen()
#include<malloc.h>//malloc()
intFileCreate(char*filePath,char*fileContext)
{
FILE*fp;
fp=fopen(filePath,"w+");
if(fp)
{
fwrite(fileContext,strlen(fileContext),1,fp);
fclose(fp);
return0;
}
return1;
}
char*FileRead(char*filePath)
{
FILE*fp;
longintfsize;
char*fileContext;
fp=fopen(filePath,"r");
if(fp)
{
fseek(fp,0,SEEK_END);
fsize=ftell(fp);
rewind(fp);
fileContext=(char*)malloc(fsize+1);//注意释放内存
fread(fileContext,fsize,1,fp);
*(fileContext+fsize)='