假设我有一个我想读的文件。
./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;
}
已编辑:
使用gcc进行编译时
gcc program.c
program.c:无法识别文件:无法识别文件格式
我的错误是什么。
答案 0 :(得分:1)
//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);
}
试试这个。
答案 1 :(得分:0)
是
但如果您有疑问,可以尝试在argv
中打印这些内容。