我的程序需要解析命令行参数,然后读取文件的内容和/或将这些内容写入另一个。用户必须使用flags输入命令,其中i表示读取文件,o表示写入,如下所示:
./program -isample -ofile
错误:
warning: passing argument 1 of ‘fgets’ from incompatible pointer type
warning: passing argument 1 of ‘fputc’ makes integer from pointer without a cast
非常感谢任何帮助!
#include <stdio.h>
#include <unistd.h>
int main (int argc, char *argv[])
{
int opt = 0;
FILE *file = NULL;
FILE *text = NULL;
char ch[200];
while ((opt = getopt(argc, argv, "i:o:")) != -1)
{
switch(opt)
{
case 'i':
{
file = fopen(argv[1], "r");
while(fgets(ch, 200, file) != EOF)
{
printf("%s\n",ch);
}
fclose(file);
}
break;
case 'o':
{
file = fopen(argv[1], "r");
text = fopen(argv[2], "w");
do
{
ch = fgets(file);
fputc(ch, text);
}while (ch != EOF);
fclose(file);
fclose(text);
}
break;
case '?':
{
if (optopt == 'i')
{
printf("\nMissing mandatory input option");
}
else if (optopt == 'o')
{
printf("\nMissing mandatory output option");
}
else
{
printf("\nInvalid option received");
}
}
break;
}
}
printf("\n");
return 0;
}
答案 0 :(得分:2)
您的计划有几个问题:
-o
选项后可能有-i
个选项。optarg
fgets
在文件末尾返回NULL
printf
会复制\n
,您应该使用fputs
。fputc
没有缓冲区fgets
有3个参数。以下是更正后的版本:
#include <stdio.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
char *infile = NULL;
char *outfile = NULL;
FILE *file = stdin;
FILE *text = stdout;
char ch[200];
while ((opt = getopt(argc, argv, "i:o:")) != -1) {
switch (opt) {
case 'i':
infile = optarg;
break;
case 'o':
outfile = optarg;
break;
case '?':
if (optopt == 'i') {
fprintf(stderr, "Missing mandatory input option\n");
} else
if (optopt == 'o') {
fprintf(stderr, "Missing mandatory output option\n");
} else {
fprintf(stderr, "Invalid option received\n");
}
break;
}
}
if (infile) {
file = fopen(infile, "r");
if (file == NULL) {
fprintf(stderr, "cannot open input file %s: %s\n",
infile, strerror(errno));
exit(1);
}
}
if (outfile) {
text = fopen(outfile, "r");
if (text == NULL) {
fprintf(stderr, "cannot open output file %s: %s\n",
outfile, strerror(errno));
exit(1);
}
}
while (fgets(ch, 200, file) != NULL) {
fputs(ch, text);
}
fclose(file);
fclose(text);
return 0;
}