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:
In other words,
argv[1]is always the filename,argv[2]is the one that needs to be set to-nif 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:
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.In addition, your
ifstatement is wrong as anor, it should be anand. It’s guaranteed thatargcwill either not be 2 or not be 4, since it can’t be both at the same time.I would start with something like: