[求助]main从命令行获取参数用来打开文件
现在需要写一个C program,从命令行中获取所要读取的文件名以及一次性在屏幕显示的文件内容的行数。比如说输入 test.exe testfile.txt 3 就等于读取testfile.txt并且一次在屏幕上显示说其中的3行内容。我的code是这样写的,但是怎么也compile不过,实在不明白是哪里出了问题,还请大家指教!另外,如果我想再增加一个功能:第一次显示3行内容后,让程序等待一个键盘输入,如果按下空格键还能继续显示3行直到文件结束。应该怎样修改code呢?? 先谢过了!!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LENGTH 256
int main(int argc, char *argv[])
{
char buf[LENGTH];
FILE *fileOp;
int loopCount, lineCount;
if ((fileOp = fopen(argv[1], "r")) == NULL)
{
fprintf(stderr,"Can't open file.\n");
exit(EXIT_FAILURE);
}
lineCount = *argv[2];
for(loopCount = 1; loopCount <= lineCount; loopCount++)
{
if (fgets (buf, 122, fileOp) != NULL )
puts(buf);
else
{
fprintf(stderr,"Format error.\n");
exit(EXIT_FAILURE);
}
}
fclose(fileOp);
return 0;
}
lineCount = *argv[2]; => lineCount = atoi(argv[2]);
另外做下参数个数的判断,增加程序的健壮性。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#define LENGTH 256
int main(int argc, char *argv[])
{
char buf[LENGTH];
char file[20];
FILE *fp = NULL;
int loopcount, lineno;
if (argc != 3) {
fprintf(stderr, "usage:%s 文件名 显示行数\n", argv[0]);
exit(-1);
}
memset(file,0x00, sizeof(file));
memcpy(file, argv[1], strlen(argv[1]));
lineno = atoi(argv[2]);
if ((fp = fopen(file, "r")) == NULL) {
fprintf(stderr, "fopen() error:[%s]", strerror(error));
exit(-1);
}
for (loopcount = 0; loopcount < lineno; loopcount++) {
if (fgets(buf, sizeof(buf), fp) == NULL) {
fprintf(stderr, "fgets() error: [%s]", strerror(errno);
exit(-1);
} else {
fprintf(stdout, "%s", buf);
}
}
return 0;
}
[解决办法]
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LENGTH 256
int main(int argc, char *argv[])
{
char buf[LENGTH];
FILE *fileOp;
int loopCount, lineCount;
if ((fileOp = fopen(argv[1], "rt")) == NULL)
{
fprintf(stderr,"Can't open file.\n");
exit(EXIT_FAILURE);
}
lineCount = atoi(argv[2]);
while(1)
{
for(loopCount = 1; loopCount <= lineCount; loopCount++)
{
if (fgets (buf, 122, fileOp) != NULL )
puts(buf);
else
{
goto quit;
}
}
getchar();
}
quit:
fclose(fileOp);
return 0;
}