2012-06-25 32 views
1

簡單的fopen操作似乎不起作用。 perror返回 - 無效的參數。什麼可能是錯的。fopen返回null - Perror打印無效參數

我有一個名爲abc.dat的R:ascii文件。

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

     return 1; 
    } 
} 

輸出:發生

以下錯誤:無效的參數。

+1

escape \,即它應該是\\ – mlt

+2

除了使用下面回答的'\\'外,還可以使用正斜槓字符,即「R:/abc.dat」。 – gavinb

回答

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

你需要逃避反斜槓的文件名參數:

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

這是因爲從字面上看 - UNnescaped - \a控制字符,通常意味着bell,即聲音/顯示系統警報;這是文件名中的無效字符。

參見Bell character

在C程序設計語言(於1972年創建的),鐘形字符可以被放置在一個字符串或字符以\常數。 (「A」代表「警告」或「聽得見」,被選中,是因爲\ b體已用於退格字符。)

2

你一定要逃逸文件名中的反斜槓:

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