将char添加到数组中并返回

时间:2017-07-21 05:46:47

标签: c arrays char

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

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

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 file\n");
    } 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;
}

我通过以下方式访问fileRead:

...
        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++;
...

1 个答案:

答案 0 :(得分:0)

逐行读取文件的示例然后将非空行存储到数组中(指向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("%s\n", output[i]);
        free(output[i]);//Discard after being used
    }

    return 0;
}