cwindows32-bitlcc-win32

open file path from other file in c


i am trying to open a file handler to a path i got from file, i have input file which has a full path in it for example : c:\def\es1.txt

i replaced the "\" char to double "\" so it will fit string format and then i am using :

myfile = fopen("temp.txt", "r");

while (fgets(line, line_size, myfile) != NULL){


    printf("==============================\n");
    printf(line);
    system("PAUSE\n");
    mbstowcs(wtext, line, strlen(line) + 1);//Plus null
    _tprintf(wtext);


    LPWSTR ptr = wtext;
    hFile = CreateFile(wtext,                // name of the write
        GENERIC_WRITE,          // open for writing
        0,                      // do not share
        NULL,                   // default security
        OPEN_EXISTING,             // create new file only
        FILE_ATTRIBUTE_NORMAL,  // normal file
        NULL);                  // no attr. template

    if (hFile == INVALID_HANDLE_VALUE)
    {
        DisplayError(TEXT("CreateFile"));
        _tprintf(TEXT("Terminal failure: Unable to open file \"%s\" for write.\n"), wtext);
        return;

    }
    else {
        printf("yes!!!!!!!\n");
    }

when the command _tprintf(wtext); occurs i see the string as it should be: "c:\def\es1.txt"

but the CreateFile command fails:

FATAL ERROR: Unable to output error code.
ERROR: CreateFile failed with error code 123 as follows:
The filename, directory name, or volume label syntax is incorrect.
Terminal failure: Unable to open file "c:\\def\\es1.txt
" for write.

when i replace the wtext variable in CreateFile with :L"c:\\def\\es1.txt" it works fine, what is the problem?


Solution

  • Are you sure that your file which contains the path doesn't contains any special char at the end ? Like a \r or \n ?

    You can print the strlen and know if your string contains only classic char.