我刚刚开始了一个学习 C 的小项目,但遇到了一些问题。 尝试从 stdin 读取文件并将字符串保存到具有指定键的列表中。
文件结构如下:
1sfa23sab:1najsf9,aksfafio2413,asfjla2345,asjfiao242
25kldg:asfkn36,akal,l,slgjii90345-234
我已经设法像这样逐个字符地读取文件:
while ((c = fgetc(stdin)) != EOF )
{
create_list(c);
}
并为我的列表定义了一个特殊的数据类型:
typedef struct data_id
{
char id;
int marker;
int key;
void* ptr;
} data_id;
data_id *nodeList;
我想保存这些字符,直到“:”、“-”、“,”或“LF/CR”在我的列表中作为一个带有特定键的 id 条目出现。所以每个ID也应该有一个键。 “-”后面的部分是一个标记,也应该保存在列表中。 例如am 条目应该像 id=slgjii90345, key=10 and marker=234 ...
到目前为止我编写的 create_list 函数是:
void create_list(input){
nodeList = malloc(sizeof *nodeList * 10);
if (islower(input) || isdigit(input)){
if (m_flag == true && isdigit(input)){
nodeList[num_id].marker += (char)input;
printf("%d", nodeList[num_id].marker);
}
else{
nodeList[num_id].id += (char)input;
m_flag = false;
}
}
else if (input == '-')
{
m_flag = true;
printf("\ndash detected, marker follows: ");
}
else if (input == '\n' || input == ',' || input == ':')
{
// printf("\nnext entry follows:\n");
nodeList[num_id].marker = 0;
nodeList[num_id].key = num_id;
num_id++;
m_flag = false;
}
// printf("%d", nodeList[num_id].marker);
}
答案 0 :(得分:0)
本回答基于原题帖;评论中指出了几个错误。这是您的代码的一个可用变体:
typedef struct data_id
{
char id[13]; // allow strings up to length 12
int key;
} data_id;
data_id *nodeList; // accessible and persistent outside create_list
int num_id;
void create_list(char input[])
{
int c = num_id++; // index of created node
nodeList = realloc(nodeList, sizeof *nodeList * num_id);
if (!nodeList) exit(1);
strcpy(nodeList[c].id, input);
nodeList[c].key = num_id;
printf("node_id: %s\n", input);
printf("key: %d\n", num_id);
}
要读取具有给定分隔符的文件并为每个 id 调用 create_list
,您可以使用:
for (char c[13]; scanf("%12[^-:,\n]%*c", c) != EOF; ) create_list(c);
<块引用>
有没有办法让 char id[]
变量具有动态增长的长度?
当然有很多方法。最简单的是,如果您有符合 POSIX.1-2008 的 scanf
- 那么您可以使用 m
修饰符让它分配足够大小的缓冲区:
typedef struct data_id
{
char *id; // allows strings of any length
int key;
} data_id;
…
nodeList[c].id = input; // instead of strcpy(nodeList[c].id, input);
…
for (char *c; scanf("%m[^-:,\n]%*c", &c) != EOF; ) create_list(c);