从c中的其他文件打开文件路径

时间:2015-03-10 13:34:09

标签: c windows 32-bit lcc-win32

我正在尝试打开文件处理程序到我从文件中获取的路径, 我有输入文件,其中有一个完整的路径,例如: C:\ DEF \ es1.txt

我将“\”字符替换为“\”,因此它将符合字符串格式,然后我正在使用:

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");
    }

当命令_tprintf(wtext);发生我看到它应该是的字符串: “C:\ DEF \ es1.txt”

但CreateFile命令失败:

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.

当我将CreateFile中的wtext变量替换为:L"c:\\def\\es1.txt"时 它工作正常,有什么问题?

3 个答案:

答案 0 :(得分:2)

您确定包含路径的文件最后是否包含任何特殊字符?像\ r或\ n?

您可以打印strlen并知道您的字符串是否只包含经典字符。

答案 1 :(得分:1)

  

我将“\”字符替换为“\”,因此它将适合字符串格式

字符串中的反斜杠是反斜杠。它们必须在字符串文字中进行转义并不意味着它们必须在您处理的每个字符串中加倍。换句话说,"\\"是一个字符串文字,只包含一个反斜杠。

带有双反斜杠的名为c:\\def\\es1.txt的文件似乎不存在,因此打开失败。至少那是我猜的。我不熟悉Windows;在Linux下,文件名中的双斜杠被解释为一个斜杠。

答案 2 :(得分:0)

谢谢大家,这是换行符,需要清除char var:

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


        printf("==============================\n");
        printf(line);


        //solution
        char deststring[BUFFER];
        memset(deststring, '\0', sizeof deststring);
        strncpy(deststring, line, strlen(line) - 1);


        mbstowcs(wtext, deststring, strlen(deststring) + 1);//Plus null
        _tprintf(wtext);
相关问题