Home > Back-end >  File Not Opening in C?
File Not Opening in C?

Time:08-29

I am tried to use read/write/append modes with both fprintf and fscanf, and they'r not working. My The location of the folder where I've saved my file is ''C:\coding projects\test\Assignment Template'' and the name of the file is ''Assignment Template.txt''.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char str[500];
    FILE *ptr;
    ptr=fopen("C:\coding projects\test\Assignment Template\Assignment template.txt","r");

    fscanf(ptr,"%s",str);

    return 0;
}

ps, I also tried to use the location of folder only without file name, also tried to use the name of the file only without folder location, but none of it seems to be working.

CodePudding user response:

As pointed out by others, the several "single '\'" in the pathname to your file are wrong. You need to replace each "\" with "\\" OR with "/". Both these solutions would work.

The second idea is that "not working" is not a helpful diagnostic. To follow that with "nothing happened" does not supply any extra information.

Here is an example showing how to write this functionality so that you can at least understand where a problem might be occurring.

int main()
{
    // Separate the filepath so it can be used in error message if necessary.
    char *fname = "C:/coding projects/test/Assignment Template/Assignment template.txt";
    char str[ 500   1 ]; // One extra for trailing '\0'

    // temporary debugging report to confirm pathname is as expected.
    printf( "Attempt open of '%s'\n", fname );

    FILE *fp = fopen( fname, "r" );
    // ALWAYS test return values for possible errors
    if( fp == NULL ) {
        // Able to report what went wrong
        fprintf( stderr, "Failed to open %s\n", fname );
        exit( EXIT_FAILURE );
    }

    // fscanf returns how many variables were 'satisfied'
    // use that information
    // Also, set a limit that won't overflow the buffer being filled
    int num = fscanf( fp, "P0s", str );

    // 'temporary' diagnostic "debugging" report to the console
    printf( "Loaded %d items\n", num );

    // clean up
    fclose( fp );

    return 0;
}

This is not "debugging with print statements"... To move forward developing code, one adds-or-modifies only a VERY few lines of code, then TESTS the consequences of those changes before adding/modifying a few more lines. "Incremental development". 'Testing' involves having clear expectations of what should happen and "seeing" if those expectations have been met. Had you printed the string that is the pathname of the file you want to open, you would have seen a problem before writing one more line of code. "Slowly and methodically, ALWAYS testing/checking."

CodePudding user response:

Use double backslash to escape backslash.

C:\\coding projects.....
  • Related