Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/62.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/jquery-ui/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 如何使用file*fp和fopen读取文件?_C - Fatal编程技术网

C 如何使用file*fp和fopen读取文件?

C 如何使用file*fp和fopen读取文件?,c,C,所以对于这个作业,我应该阅读一个文件,并处理内容。现在我只想能够打开文件,读取它并打印出它有多少行。我相信我有正确的代码来这样做,但我不知道如何“读取”或连接到我的程序之外的文件!我正在使用 FILE *fp = NULL; fp = fopen (); 对不对?这就是如何打开/连接到文件?但不确定这是做什么的,以及它如何连接到程序外的文件。为了读取文件,我让用户输入他们的文本文件,如 printf ("Enter the name of the data file: "); scanf (

所以对于这个作业,我应该阅读一个文件,并处理内容。现在我只想能够打开文件,读取它并打印出它有多少行。我相信我有正确的代码来这样做,但我不知道如何“读取”或连接到我的程序之外的文件!我正在使用

FILE *fp = NULL; 
fp = fopen ();
对不对?这就是如何打开/连接到文件?但不确定这是做什么的,以及它如何连接到程序外的文件。为了读取文件,我让用户输入他们的文本文件,如

printf ("Enter the name of the data file: ");
scanf ("%[^\n]", &filename);
然后去读我放在

fp = fopen("&filename", "r");
但这似乎不对,也不起作用。有人能解释我做错了什么,以及我如何读取用户输入的文件吗?我在一个SSH矩阵组中,如果这有意义的话,比如我使用SSH终端登录putty?不知道该怎么解释,但这是我学校的事

fp = fopen("&filename", "r");
文件名
是可变的,为什么要在
中传递它?
双引号

试试下面这样的方法:

char filename[50]; // need a character array or buffer to hold the filename

printf ("Enter the name of the data file: ");
scanf ("%[^\n]", filename);   // no & operator
现在使用

fp = fopen(filename, "r");   // filename variable should contain complete path 

                              //with the actual file name
我认为这应该行得通

您还需要检查
fp
as

if(fp == NULL)   // It's always a safe way to proceed
   printf("Error in file opening\n");