c - 将标记存储到数组中以便稍后作为参数传递

标签 c arrays stringtokenizer

我有一个已经标记化的文件,但我需要将每个标记存储在一个数组中以供以后用作参数。我该如何去做呢?

//         Read in File           //
FILE *fp;
char buffer[100];

fp = fopen(params, "r");

printf("Here is filename...");
printf("%s\n", params);

fseek(fp, 0, SEEK_END);
//byte_size = ftell(fp);
rewind(fp);

if (fgets(buffer,sizeof(buffer),fp) != NULL)
{
    char*p, *b;
    b = buffer;
    printf("parsing %s", buffer);
    while ((p = strsep(&b, ",")) != NULL)
    {
        printf("param: %s\n",p);
    }
}
fclose(fp);

最佳答案

使用链表并稍后将其转换为数组可能会很好,因为我们不知道有多少个标记。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *strsep(char **stringp, const char *delim);

typedef struct node_tag {
    char *str;
    struct node_tag* next;
} list_node;

list_node* create_node(const char *str) {
    list_node* n = malloc(sizeof(list_node));
    if (n == NULL) exit(1);
    if (str == NULL) {
        n->str = NULL;
    } else {
        n->str = malloc(sizeof(char) * (strlen(str) + 1));
        if (n->str == NULL) exit(1);
        strcpy(n->str, str);
    }
    n->next = NULL;
    return n;
}

int main(void) {
    const char *params = "dummy";
    FILE *fp;
    char buffer[100];
    list_node *head = NULL;
    list_node **tail = &head;
    unsigned int count = 0;
    unsigned int i;
    char **array;
    fp = stdin;//fopen(params, "r");
    printf("Here is filename...");
    printf("%s\n", params);
    fseek(fp, 0, SEEK_END);
    //byte_size = ftell(fp);
    rewind(fp);

    if (fgets(buffer,sizeof(buffer),fp) != NULL)
    {
        char*p, *b;
        b = buffer;
        printf("parsing %s", buffer);
        while ((p = strsep(&b, ",")) != NULL)
        {
            printf("param: %s\n",p);
            *tail = create_node(p);
            tail = &(*tail)->next;
            count++;
        }


    }

    array = malloc(sizeof(char*) * count);
    if (array == NULL) return 1;
    for (i = 0; i < count && head != NULL; i++) {
        list_node *next = head->next;
        array[i] = head->str;
        // Don't free(head->str) because it is used
        free(head);
        head = next;
    }

    for (i = 0; i < count; i++) {
        printf("array[%u] = %s\n", i, array[i]);
    }
    for (i = 0; i < count; i++) free(array[i]);
    free(array);

    //fclose(fp);
    return 0;
}

关于c - 将标记存储到数组中以便稍后作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32685947/

相关文章:

c - 如何将结构数组的地址传递给函数?

c - 在 linux 中调用 pthread_create() 结果为 'Segmentation fault '

javascript - 查找二维数组中最长的元素

java - StringTokenizer 不显示数字末尾的 0

autocomplete - Elasticsearch:查找子串匹配

c - 如何将某些字符从一个字符串传输到另一个字符串?

c++ - 如何在 OpenCV 中获取网络摄像头 fps 速率?

javascript - 在javascript中搜索json对象的递归函数

php - 通过 PHP(多维数组)合并非常复杂的 SQL 数据结果

go - golang 中电子邮件模板的 Parse Html token 方法是什么?