0

Thanks for all answers, now i have a new question: why whatever i input the output is always GREAT? Like if the input is not pokemon.csv, then it should returns me "pokemon.csv file is not found. Please enter the name of the file again or enter 1 to exit" instead.
Is there a issue with my fopen format or logic?

int pexists();
int main(){
    FILE *pokemon;
    int rc = 0;
    char file_name[30];
    
    printf("Please enter the NAME of the file that containing the Pokemon        descriptions:\n");
    scanf("%c", file_name);
    rc = pexists();
    return 0;
}
/*********************************************************************/
//function that do the exist checking.

int pexists(){
    FILE *pokemon;
    //int rc = 0;
    // open the file by reading.
    pokemon = fopen("file_name", "r");
    if(!pokemon){
        printf("Pokemon file is not found. Please enter the name of the file again or enter 1 to exit.\n");
        exit(1);
    }
    else{
        printf("GREAT\n");
    }
    fclose(pokemon);
}
朱旭翔
  • 25
  • 4
  • Did you intend to open the file written into the terminal? Your code always opens "pokemon.CSV". Should it instead fopen file_name? – Caius Jard Jul 24 '21 at 06:41
  • also put `fclose(pokemon)` above `return 0;`, otherwise its not gonna be reached – urmat abdykerimov Jul 24 '21 at 08:14
  • Does this answer your question? [What's the best way to check if a file exists in C?](https://stackoverflow.com/questions/230062/whats-the-best-way-to-check-if-a-file-exists-in-c) and [Checking a file exists in C](https://stackoverflow.com/questions/9482770/checking-a-file-exists-in-c) and [Fastest way to check if a file exist using standard C++/C++11/C?](https://stackoverflow.com/questions/12774207/fastest-way-to-check-if-a-file-exist-using-standard-c-c11-c) –  Jul 24 '21 at 08:56
  • Two changes are required. (1) replace "pokemon.csv" for file_name inside the fopen and (2) move the fclose(pokemon) inside the else{} to avoid segmentation fault. Moreover be aware that there is a limitation in file name's length. – MCL Jul 24 '21 at 15:31
  • Thanks for all answers, would anyone please help me out with my new question? – 朱旭翔 Jul 25 '21 at 21:39

0 Answers0