fopen返回null – Perror打印无效参数

简单的fopen操作似乎不起作用。 perror返回 – 参数无效。 可能有什么不对。

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

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

输出:

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

逃避你的\ 。 在字符串中使用时必须为\\

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

否则, fopen看到字符串包含\a “alert”转义序列,它是一个无效的参数。

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

 \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) 

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

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

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

见贝尔字符 :

在C编程语言(1972年创建)中,可以使用\ a将钟形字符放在字符串或字符常量中。 (’a’代表“alert”或“audible”并被选中,因为\ b已经用于退格符。)

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

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