C - 将 char 添加到数组中并返回



我是c的新手,正在尝试理解指针。 在这里,我打开一个文件并阅读给定的行。我试图将这些行附加到数组中并从函数返回它。我似乎没有正确附加或访问数组。输出[计数] = 状态;给出字符和字符 * 不匹配的错误。

我本质上是试图获取一个数组,其中包含一个文件给出的单词列表,其中数组中的每个元素都是一个单词。

char *fileRead(char *command, char output[255]) {
int count = 0;
char input[255];
char *status;
FILE *file = fopen(command, "r");
if (file == NULL) {
printf("Cannot open filen");
} else {
do {
status = fgets(input, sizeof(input), file);
if (status != NULL) {
printf("%s", status);
strtok(status, "n");
// add values into output array
output[count] = status;
++count;
}
} while (status);
}
fclose(file);
return output;
}

我通过以下方式访问文件读取:

...
char commandArray[255];
char output[255];
int y = 0;
char *filename = "scriptin.txt";
strcpy(commandArray, fileRead(filename, output));
// read from array and pass into flag function
while (commandArray[y] != NULL) {
n = flagsfunction(flags, commandArray[y], sizeof(buf), flags.position, &desc, &parentrd, right, left, lconn);
y++;
...

从文件中读取的示例 逐行读取,然后将非空行存储到数组中(指向char的指针数组(如char*((

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//for it does not exist because strdup is not a standard function. 
char *strdup(const char *str){
char *ret = malloc(strlen(str)+1);
if(ret)
strcpy(ret, str);
return ret;
}
//Read rows up to 255 rows
int fileRead(const char *filename, char *output[255]) {
FILE *file = fopen(filename, "r");
if (file == NULL) {
perror("Cannot open file:");
return 0;
}
int count = 0;
char input[255];
while(count < 255 && fgets(input, sizeof(input), file)) {
char *line = strtok(input, "n");
if(line)//When it is not a blank line
output[count++] = strdup(line);//Store replica
}
fclose(file);
return count;
}
int main(void){
char *output[255];//(`char *` x 255)
int number_of_read_line = fileRead("data.txt", output);
for(int i = 0; i < number_of_read_line; ++i){
printf("%sn", output[i]);
free(output[i]);//Discard after being used
}
return 0;
}

最新更新