Ich übe derzeit Datei I/O in C. Ich erstellte ein Programm, wo ich eine Datei und extrahieren Sie Daten von ihm, und ich möchte eine Option, um die Datei zu ändern wird gelesen. Das Problem, das mir begegnet, ist, dass ich zum Beispiel zwei Dateien habe: sample1.txt
und sample2.txt
. Wenn ich sample1.txt
als die erste Datei wählte, die gelesen werden soll, und dann wollte ich die Datei zu sample2.txt
ändern, was schließlich passiert, ist, dass der Dateiname nicht zu sample2.txt
ändert, sondern stattdessen immer was immer Dateiname die erste Datei hat.Ändern des aktuellen Dateinamens zu einem anderen mit fopen
Hier ist mein Code:
#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;
}
Könnte jemand mir erklären, warum versagt mein Code hält? Jede konstruktive Kritik, Hinweise zu File I/O wird geschätzt.
Sie sind ein 'break' statment nach dem' Fall fehlen 1 'und der Standard ein –
@JoaoTorres Danke, bearbeiten den Code. – Noobplox23
@ Noobplox23 ** Einzug ** Ihr Code! – gsamaras