⑴ 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)='