C 基本头命令

标签 c linux tail head

我正在尝试为我的编程类(class)重新创建 linux 的头部和尾部命令。 我们刚开始使用 C,所以我对分配内存和指针的想法还很陌生。 我想知道为什么这不起作用。

#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];

任何额外的见解也会有所帮助。

最佳答案

我觉得这样写比较好:

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

或者(如果你不想复制字符串):

char* fileName = argv[1];

关于C 基本头命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12361558/

相关文章:

linux - 无法加载库

python - 如何在 python 中生成另一个进程并捕获输出?

linux 使用带分隔符的 watch 命令

linux - 如何使用 tail & head 和管道打印 2 个值之间的行?

C 链表头指针正在改变数据值

C文件比较

c - 警告 : ‘struct tag’ declared inside parameter list will not be visible outside of this definition or declaration void func(struct tag v);

c - 找出出现次数超过 N/3 的数

linux - Ubuntu Docker 容器立即停止,Dockerfile 出现问题?

linux - tail -f 总是使用 inotify 吗?