我正在尝试制作一个带有命令行参数的主函数,该参数允许该程序打开两个文件(命令行中提供的路径),并将两个文件一次一行地组合成一个输出。提供的第一个文件是文本行。删除所有结尾的空白,制表符和换行符。第二个文件是一个数字列表,在打印到输出时,每个数字都必须加一个。另外,这两列应由制表符分隔。
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
const int MAXLEN = 4096;
const int MAXLINES = 10;
int main(int argc, char *argv[]) {
char buffer[MAXLEN];
char buffer2[MAXLEN];
FILE *fp = fopen(argv[1], "r");
FILE *fp2 = fopen(argv[2], "r");
if (!fp || !fp2) {
perror ("Not Found");
exit (EXIT_FAILURE);
}
int n = 0;
while((n < MAXLINES) && (fgets (buffer, sizeof (buffer), fp)) && (fgets(buffer2, sizeof (buffer2), fp2))) {
printf("%s\t%s", buffer, buffer2);
n++;
}
}
fclose(fp);
fclose(fp2);
return 0;
}
例如输入和输出:
./c2 test/c2-testa test/c2-testb
Test A 11
Test B 51
Test C 91
Test D 26
Test E 17
Test F 76
这是我在gcc
命令之后收到的信息:
c2:
c2.c:53:7: warning: data definition has no type or storage class
fclose(fp);
^~~~~~
c2.c:53:7: warning: type defaults to ‘int’ in declaration of ‘fclose’ [-Wimplicit-int]
c2.c:53:7: warning: parameter names (without types) in function declaration
c2.c:54:7: warning: data definition has no type or storage class
fclose(fc2);
^~~~~~
c2.c:54:7: warning: type defaults to ‘int’ in declaration of ‘fclose’ [-Wimplicit-int]
c2.c:54:7: warning: parameter names (without types) in function declaration
c2.c:56:7: error: expected identifier or ‘(’ before ‘return’
return 0;
^~~~~~
c2.c:58:7: error: expected identifier or ‘(’ before ‘}’ token
}
^
make: *** [Makefile:31: c2.o] Error 1
答案 0 :(得分:2)
您所做的是将第二个文件的所有行打印为第一个文件的每一行(嵌套循环)。您的循环应如下所示:
int n = 0;
while((n < MAXLINES) && (fgets (buffer, sizeof (buffer), fp)) && (fgets(buffer2, sizeof (buffer2), fp2))) {
printf("%s\t%s", buffer, buffer2);
n++;
}
请注意,这不会处理“删除结尾的空白”。您可能需要为此做一些额外的处理。
此外,打开文件后的条件应该为if(!fp || !fp2)
,以确保两个文件都可以打开!