我目前正在C語言中練習文件I/O。我創建了一個程序,我從中獲取文件並從中提取數據,我想要一個選項來更改文件正在閱讀。我遇到的問題是,例如我有兩個文件:sample1.txt
和sample2.txt
。如果我選擇sample1.txt
作爲第一個要讀取的文件,然後我想將文件更改爲sample2.txt
,最終發生的情況是文件名不會更改爲sample2.txt
,而是始終保留第一個文件具有的文件名。使用fopen將當前文件名更改爲另一個文件
這裏是我的代碼:爲什麼我的代碼一直沒有給我
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <assert.h>
#include <time.h>
#include <ctype.h>
int main()
{
char file_location[100]={0};
char new_location[100]={0};
FILE* fPointer=NULL;
int choice;
printf("Enter the filename that you wish to open.\n");
scanf("%[^\n]s",file_location); // I enter sample1.txt//
printf("%s\n",file_location);
fPointer=fopen(file_location,"r"); // success,sample1.txt is currently being read.//
if (fPointer==NULL)
{
printf("File error!,invalid file name! program will now exit.\n");
exit(0);
}
else
{
printf("Success!\n");
}
printf("Do you want to change the file being read\n); //Now I want to change the file,from sample1.txt to sample2.txt//
prinft("Enter 1 to change, 0 to exit the program\n);
do{
scanf("%d",&choice);
printf("You entered %d\n",choice);
if(choice<0||choice>1)
{
printf("Error,please choose between 1 and 0\n");
}
}while(choice!=1||choice!=0);
switch(choice) // I enter 1,go to case1//
{
case 0:
printf("Exiting program now\n");
exit(0);
break;
case 1:
fclose(fPointer);
printf("Enter the filename that you wish to open.\n");
scanf("%[^\n]s",new_location); //scanf does not even prompt me to enter a string.//
printf("%s\n",new_location); //nothing prints//
fPointer=fopen(new_location,"r"); // fpointer still points to sample1.txt//
break;
}
return 0;
}
誰能解釋一下嗎? 任何建設性的批評,關於文件I/O的筆記表示讚賞。
你缺少了'1'情況下,默認一個 –
@JoaoTorres謝謝後'break' statment,編輯的代碼。 – Noobplox23
@ Noobplox23 **縮進**你的代碼! – gsamaras