C 从命令行读取文件?

C 从命令行读取文件?,c,unix,C,Unix,假设我有一个我想读的文件 ./a.out file // where file is a argument 该计划是: //program.c #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { char ch, file_name[25] = argv[1]; //???

假设我有一个我想读的文件

./a.out file // where file is a argument 
该计划是:

     //program.c

        #include <stdio.h>
        #include <stdlib.h>


        int main(int argc, char *argv[])
        {  
        char ch, file_name[25] = argv[1]; //??? Is the issue here?
        FILE *fp;

         fp = fopen(file_name,"r");  

        if( fp == NULL )
       {
          perror("Error while opening the file.\n");
          exit(EXIT_FAILURE);
       }

       printf("The contents of %s file are :\n", file_name);

       while( ( ch = fgetc(fp) ) != EOF )
          printf("%c",ch);

       fclose(fp);
       return 0;

        }
program.c:无法识别文件:无法识别文件格式

是我收到的错误。

但是如果您有疑问,可以尝试在
argv

//program.c中打印这些内容
//program.c                                                                                                                                                                                                         

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define SIZEBUF 1024

int main(int argc, char *argv[])
{
   int   fd;
   char  buffer[SIZEBUF];

  if (argc < 2)
   {
    printf("Missing file\n");
    return (EXIT_FAILURE);
   }
  fd = open(argv[1], O_RDONLY);
  if (fd == -1)
   {
     printf("Some error occured\n");
     return (EXIT_FAILURE);
   }
  printf("The contents of %s file are :\n", argv[1]);
  while(read(fd, buffer, SIZEBUF) > 0 )
    printf("%s", buffer);
  close(fd);
  return (EXIT_SUCCESS);
}
#包括 #包括 #包括 #包括 #包括 #定义SIZEBUF 1024 int main(int argc,char*argv[]) { int-fd; 字符缓冲区[SIZEBUF]; 如果(argc<2) { printf(“缺少文件\n”); 返回(退出失败); } fd=打开(argv[1],仅限Ordu); 如果(fd==-1) { printf(“发生了一些错误\n”); 返回(退出失败); } printf(“文件%s的内容为:\n”,argv[1]); while(读取(fd、缓冲区、SIZEBUF)>0) printf(“%s”,缓冲区); 关闭(fd); 返回(退出成功); }

试试这个。

为什么不编译并试试呢?我很确定它不会摧毁我们的世界。无法使用SSH atm,无法访问Unix请尝试
printf(“%s\n”,argv[1])
并查看其是否正确。这不依赖于*nix,只是为了注意:在本地运行vm。您报告的错误消息(“无法识别文件格式”)表明您试图运行错误的文件,或者您编译的文件不正确。
//program.c                                                                                                                                                                                                         

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define SIZEBUF 1024

int main(int argc, char *argv[])
{
   int   fd;
   char  buffer[SIZEBUF];

  if (argc < 2)
   {
    printf("Missing file\n");
    return (EXIT_FAILURE);
   }
  fd = open(argv[1], O_RDONLY);
  if (fd == -1)
   {
     printf("Some error occured\n");
     return (EXIT_FAILURE);
   }
  printf("The contents of %s file are :\n", argv[1]);
  while(read(fd, buffer, SIZEBUF) > 0 )
    printf("%s", buffer);
  close(fd);
  return (EXIT_SUCCESS);
}