简体   繁体   English

将评论读入动态大小的数组

[英]Reading comments into an array of dynamic size

So i have a series of comments in my markup file: 所以我在标记文件中有一系列评论:

# comment1
# comment2

I want to read these into an array to be added to a comment array in my struct. 我想将它们读入数组以添加到我的结构中的注释数组中。 I do not know the amount of comment lines in advance 我事先不知道评论行的数量

I declare the comment array in my struct as follows: 我在结构中声明注释数组,如下所示:

char *comments; //comment array

Then I am starting to read the comments in but what i've got wasn't working: 然后我开始阅读其中的评论,但是我没有用:

int c;
//check for comments
c = getc(fd);
while(c == '#') {
    while(getc(fd) != '\n') ;
    c = getc(fd);
}
ungetc(c, fd);
//end comments?

Am I even close? 我什至靠近吗?

Thanks 谢谢

First 第一

char *comments; //comment array

Is one comment not an array of comments. 是一个评论而不是评论数组。

You need to use realloc, to create an array of strings 您需要使用realloc来创建字符串数组

char**comments = NULL;
int count = 10; // initial size
comments  = realloc(comments, count);

when you get > count 当你>计数

count*=2;
comments = realloc(comments, count);// classic doubling strategy

to put a string into the array (assuming comment is a char* with one comment in it 将字符串放入数组(假设注释是一个char *,其中有一个注释

   comments[i] = strdup(comment);

You can use fgets() form <stdio> to read one line at at time. 您可以使用形式为<stdio> fgets()一次读取一行。

int num_comments = 0;
char comment_tmp[82];
char comment_arr[150][82];
while(comment_tmp[0] != '#' && !feof(file_pointer)){
    fgets(comment_tmp, 82, file_pointer);
    strcpy(comment_arr[num_comments], comment_tmp);
    num_comments++;
}

This has the limitation of only being able to store 150 comments. 这具有只能存储150条注释的限制。 This can be overcome by 1) setting a higher number there, 2) using dynamic memory allocation (think malloc/free), or 3) organizing your comments into a more flexible data structure like a linked list. 可以通过以下方法克服这一问题:1)在此设置一个更大的数字,2)使用动态内存分配(认为是malloc / free),或3)将您的注释组织为更灵活的数据结构(如链表)。

When you see that line is comment store the value of comment in comment variable just go to next line and do this loop again. 当您看到该行是注释时,将注释的值存储在注释变量中,只需转到下一行并再次执行此循环即可。 So the code : 所以代码:

char c = getc(fd);
while(c == '#') {
    while(getc(fd) != '\n') /* remove ; */ {
    *comment = getc(fd);
    ++comment;
    }
}

or use fscanf which is easier : 或使用更简单的fscanf

fscanf(fd,"#%s\n",comment); /* fd is the file */

Note that comment here is a string not an array of string. 请注意,这里的注释是一个字符串,而不是字符串数组。

For array of string it would be : 对于字符串数组,它将是:

#define COMMENT_LEN 256

char comment [COMMENT_LEN ][100];
int i = 0;
while(!feof(fd) || i < 100) {
     fscanf(fd,"#%s\n",comment[i]);
     getch(); /* To just skip the new line char */
     ++i;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM