问题
The simple fopen operation seems to not work. perror returns - Invalid argument. What could be wrong.
I have a ascii file called abc.dat in R:.
int main()
{
FILE *f = fopen("R:\abc.dat","r");
if(!f)
{
perror ("The following error occurred");
return 1;
}
}
Output:
The following error occurred: Invalid argument.
回答1:
Escape your \. It must be \\ when used in the string.
FILE *f = fopen("R:\\abc.dat","r");
Otherwise, the string is seen by fopen to be including the \a "alert" escape sequence which is an invalid argument to it.
Common escape sequences and their purposes are:
\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)
回答2:
You need to escape backslashes in the file name argument:
FILE *f = fopen("R:\\abc.dat","r");
This is because taken literally - UNnescaped - \a is a control character that typically means bell, i.e. sound/show a system alert; this is an invalid character in a file name.
See Bell character:
In the C programming language (created in 1972), the bell character can be placed in a string or character constant with \a. ('a' stands for "alert" or "audible" and was chosen because \b was already used for the backspace character.)
回答3:
You need to escape the backslash in the file name:
FILE *f = fopen("R:\\abc.dat", "r");
来源:https://stackoverflow.com/questions/11182178/fopen-returns-null-perror-prints-invalid-argument