简体   繁体   English

逐行读取文件-文件在哪里?

[英]reading in a file line by line - where is the file?

Im new to using GNU C by using Terminal on a Mac. 我是在Mac上使用Terminal来使用GNU C的新手。

I've used a standard piece of code to read in a file line by line and referring out to a file by "file.txt". 我使用了一段标准的代码来逐行读取文件,并通过“ file.txt”引用文件。

I can compile the source but when I execute the code it can't find file.txt. 我可以编译源代码,但是执行代码时找不到file.txt。 I have put the file in the the same directory as the source and executable file. 我已将该文件与源文件和可执行文件放在同一目录中。 Should I be adding a full directory path. 我应该添加完整的目录路径。 I tried :- 我试过了 :-

"/Users/Swiss/documents/swdev/projects/code_ex/file.txt" “ /Users/Swiss/documents/swdev/projects/code_ex/file.txt”

but that comes up with the same error as just using "file.txt". 但这会带来与使用“ file.txt”相同的错误。

The error I get is:- 我得到的错误是:-

-bash: ./read_file.lbl: No such file or directory -bash:./read_file.lbl:没有这样的文件或目录

and am assuming its the file.txt it can't find - or is it something else? 并假设找不到它的file.txt-还是其他东西?

The code is:- 代码是:-

#include <stdio.h>
int main ( void )
{
   static const char filename[] =  "/Users/Swiss/documents/swdev/projects/code_ex/file.txt";
   FILE *file = fopen ( filename, "r" );
   if ( file != NULL )
   {
      char line [ 128 ]; /* or other suitable maximum line size */
      while ( fgets ( line, sizeof line, file ) != NULL ) /* read a line */
      {
         fputs ( line, stdout ); /* write the line */
      }
      fclose ( file );
   }
   else
   {
      perror ( filename ); /* why didn't the file open? */
   }
   return 0;
}

Any help will be warmly welcomed. 任何帮助都将受到热烈欢迎。

Your program is correct. 您的程序是正确的。 If the source file is called read_file_lbl.c , run these commands to compile it and run it from the terminal: 如果源文件名为read_file_lbl.c ,请运行以下命令进行编译并从终端运行它:

$ gcc -Wall -o read_file_lbl read_file_lbl.c
$ ./read_file_lbl

If you compile the program with gcc read_file_lbl.c , the compiler names the executable a.out , so trying to run ./read_file_lbl fails as no such executable is found by the shell. 如果使用gcc read_file_lbl.c编译程序,则编译器将可执行文件命名为a.out ,因此尝试运行./read_file_lbl失败,因为外壳程序找不到此类可执行文件。

Note also that gcc is really a link to clang on your environment. 还要注意, gcc实际上是您环境中clang的链接。 You can check with: 您可以通过以下方式进行检查:

$ gcc --version

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM