gpt4 book ai didi

创建文件到数组函数

转载 作者:太空宇宙 更新时间:2023-11-04 06:58:43 25 4
gpt4 key购买 nike

目前我将 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com