创建文件到数组函数

标签 c

目前我将 argc、argv 和 temp 部分放入要传递的位置,当我编译时它没有返回任何错误,但是当我稍后在程序中调用该函数并向它传递一个 char 数组时。它返回堆栈转储。从我到目前为止所学到的知识来看,数组不能从函数传回,这就是我传递指针的原因。

int In2File(int argc, char *argv[], char *temp[] ){

    if (argc == 2) { //open file
        FILE *user_file;
        user_file = fopen(argv[1], "r");
        if (user_file == NULL) {
            printf("No data was found.\nEnd(Error 1)");
            exit(2);
        }
        else {
            int g = 0;//temp counter to load
            char c = 0;
            while ((c = fgetc(user_file)) != EOF && g <= tmplng - 1) { //Used Fgetc instead of fgets because Fgetc allows me to read
                *temp[g] = c;                      //until the end of the file and read each character. Even if there is an \n character.
                g++;                              // The second g < tmplng-1 is used to make sure that the \0 can be placed into the array.
            }
            printf("%s\n", temp);
            fclose(user_file);//Closed the txt file that was loaded by user in args(1)          
            printf("\nFile Loaded.\n");
        }
    }
    else if (argc > 2) { // Will exit if arguments are greater than 2.
        printf("Format: %s 'filename'", argv[0]);
        exit(1);
    }
    else {
        printf("File not provided. Enter information:\n");//If the user doesnt provide a file allow manual input.
        fgets(*temp, tmplng, stdin);
    }
}

In2File(argc,argv,temp);

有人知道我在这个函数上哪里出了问题吗?我读了一些类似的帖子,但它们是针对 C++ 和 Python 的。我还没有学过 C++,Python 与这个叫做 C 的野兽不同。

编辑:

const int tmplng = 1000; //The only variables needed
    char temp[tmplng];       //
    char temp2[tmplng];      //

    printf("Starting....\n"); //Used for testing debugging. 

最佳答案

函数的第三个参数与函数的预期不匹配。您传递的是 char [](衰减为 char *),而函数需要 char *[](等同于 char ** 作为函数参数)。

第三个参数的定义与你打算如何使用它不匹配,它是一个字符数组。

去除参数上额外的间接级别,并相应地调整函数。

int In2File(int argc, char *argv[], char temp[] ){
        ...
        while ((c = fgetc(user_file)) != EOF && g <= tmplng - 1) { 
            temp[g] = c; 
            g++;  
        }

关于创建文件到数组函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41004046/

相关文章:

c - fork /执行 : child exits when trying to redirect stdin/stdout

c - 在 GCC 中对齐 malloc()?

c - Linux 内核中的 major() 和 minor() 函数

c - 全局 const 优化和符号插入

c - 在 C 中使用 strstr() 查找最右边的匹配项

c++ - 修改文件路径以在 Printf 中使用

c - 从 'atoi' 收到未经验证的整数值

c++ - 从文件中读取十六进制值

c - dbus:嵌入式连接?

c - 查找内存缓冲区中任何未设置位的位置的快速方法