C Main management team

I am 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 am wondering why this is not working.

#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 insights would also be helpful.

+5
source share
2 answers

First of all, your use does not match the validation of your argument. According to usage, you should use one of:

head <filename>
head <filename> -n <count>

In other words, is argv[1]always the name of the file, argv[2]- this is the one that should be set to -n, if there are more than two arguments.

-, VLA ( ), , , - :

char *fileName = argv[1];

(, , fopen, ), , .

, if or, and. , argc 2, 4, .

- :

#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.

}
+2

, :

char fileName[strlen(argv[1])+1];
strcpy(fileName, argv[1]);

( ):

char* fileName = argv[1];
+3

All Articles