C基本数据head命令 [英] C Basic Head Command
问题描述
我试图重新头部,并从Linux命令尾为我的编程类。
我们刚刚开始使用C,所以我是新来分配内存和指针的想法。
我不知道为什么这是行不通的。
I'm trying to recreate the head, and tail commands from linux for my programming class. We just started using C so I'm new to the idea of allocating memory and pointers. I'm wondering why this doesn't work.
#include <stdio.h>
#include <stdlib.h>
int main(int argc,char **argv){
/* Checks if correct amount of arguements */
if(argc != 2 || argc != 4){
printf("Usage: %s head <file> \n Or: head <file> -n <number of characters>", argv[0]);
exit(-1);
}
if(strcmp(argv[1], "-n" != 0)){
char fileName[strlen(argv[1])] = argv[1];
}
}
//Compile error on char fileName[strlen(argv[1])] = argv[1];
任何额外的见解也将是有益的。
Any additional insight would also be helpful.
推荐答案
首先第一件事情,您的使用不符合您的参数检查。根据使用情况,您必须使用之一:
First things first, your usage doesn't match your argument checking. According to the usage, you must use one of:
head <filename>
head <filename> -n <count>
在换句话说,的argv [1]
是总是的文件名,的argv [2]
是需要被设置为 -n
如果有两个以上的参数之一。
In other words, argv[1]
is always the filename, argv[2]
is the one that needs to be set to -n
if there are more than two arguments.
其次,除非你想用沃拉斯(可变长度数组),你应该只设置一个指向文件名参数的东西,如:
Secondly, unless you want to use VLAs (variable length arrays), you should probably just set up a pointer to the filename argument with something like:
char *fileName = argv[1];
您不需要改变它在所有(你只可以把它传递给的fopen
,presumably),所以它试图使废另一个副本。
You don't need to change it at all (you'll just be passing it to fopen
, presumably), so it's a waste trying to make another copy.
另外,你的如果
说法是错误的,因为一个或
,它应该是一个和
。它保证的argc
将要么不为2或不为4,因为它不能在同一时间既
In addition, your if
statement is wrong as an or
, it should be an and
. It's guaranteed that argc
will either not be 2 or not be 4, since it can't be both at the same time.
我就开始是这样的:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static int usage (void) {
printf ("Usage: head <file>\n");
printf (" or: head <file> -n <number of characters>\n");
return -1;
}
int main (int argc,char *argv[]) {
char *fileName;
int lineCount;
// Checks if correct arguments
if ((argc != 2) && (argc != 4)) return usage();
if ((argc == 4) && (strcmp(argv[2], "-n" != 0)) return usage();
// Get file spec and line count
fileName = argv[1];
lineCount = (argc == 2) ? 10 : atoi (argv[3]); // or strtol for purists
if (linecount < 0) lineCount = 0;
// Now go ahead and implement the logic for head.
}
这篇关于C基本数据head命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!