2

简单的 fopen 操作似乎不起作用。perror 返回 - 无效的参数。有什么问题。

我在 R: 中有一个名为 abc.dat 的 ascii 文件。

int main()
{
    FILE *f = fopen("R:\abc.dat","r");
    if(!f)
    {
        perror ("The following error occurred");

        return 1;
    }
}

输出:

发生以下错误:参数无效。

4

3 回答 3

5

逃离你的\. \\在字符串中使用时必须是。

FILE *f = fopen("R:\\abc.dat","r");

否则,该字符串被视为fopen包含\a“警报”转义序列,这是对其无效的参数。

常见的转义序列及其用途是:

\a  The speaker beeping
\\  The backslash character

\b  Backspace (move the cursor back, no erase)
\f  Form feed (eject printer page; ankh character on the screen)
\n  Newline, like pressing the Enter key
\r  Carriage return (moves the cursor to the beginning of the line)
\t  Tab
\v  Vertical tab (moves the cursor down a line)
\’  The apostrophe
\”  The double-quote character
\?  The question mark
\0  The “null” byte (backslash-zero)
\xnnn   A character value in hexadecimal (base 16)
\Xnnn   A character value in hexadecimal (base 16)
于 2012-06-25T00:07:51.360 回答
3

您需要在文件名参数中转义反斜杠:

 FILE *f = fopen("R:\\abc.dat","r");

这是因为从字面上理解 - 未转义 -\a是一个控制字符,通常表示bell,即声音/显示系统警报;这是文件名中的无效字符。

参见贝尔字符

在 C 编程语言(创建于 1972 年)中,钟字符可以用 \a 放在字符串或字符常量中。('a' 代表 "alert" 或 "audible",之所以选择它是因为 \b 已用于退格字符。)

于 2012-06-25T00:08:03.483 回答
2

您需要转义文件名中的反斜杠:

FILE *f = fopen("R:\\abc.dat", "r");
于 2012-06-25T00:08:15.060 回答