[英]C Basic Head Command
I'm trying to recreate the head, and tail commands from linux for my programming class. 我正在尝试为我的编程类从linux重新创建head和tail命令。 We just started using C so I'm new to the idea of allocating memory and pointers.
我们刚刚开始使用C,因此我对分配内存和指针的想法是陌生的。 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. 任何其他见解也将有所帮助。
I think it's better to write: 我认为最好写:
char fileName[strlen(argv[1])+1];
strcpy(fileName, argv[1]);
or (if you don't whant to make a copy of string) : 或者(如果您不希望复制字符串):
char* fileName = argv[1];
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>
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. 换句话说,
argv[1]
始终是文件名,如果有两个以上的参数,则argv[2]
是需要设置为-n
的文件名。
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: 其次,除非您要使用VLA(可变长度数组),否则可能应该只使用以下内容设置指向filename参数的指针:
char *fileName = argv[1];
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. 您根本不需要更改它(大概只是将其传递给
fopen
),因此尝试制作另一个副本是一种浪费。
In addition, your if
statement is wrong as an or
, it should be an and
. 另外,
if
您的if
陈述式错误为or
,则应该为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. 可以保证
argc
不能为2或不为4,因为它不能同时为两个。
I would start with something like: 我将从以下内容开始:
#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.
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.