gpt4 book ai didi

C - 将输入文件解析为行和字符

转载 作者:行者123 更新时间:2023-11-30 17:38:27 25 4
gpt4 key购买 nike

我正在尝试编写一个 C 程序来解析输入文件,以便解析各个行,然后在每一行中进一步解析各个字符并将其存储在 struct 中的不同变量中。到目前为止,这是我的代码(我已经设法解析单个字符,而不考虑它们位于哪一行):

/* create struct instances */
/* file open code */
...
int currentChar = fscanf(fp, "%s", storageArray);
while (currentChar != EOF) {
printf("%s\n", storageArray);
currentChar = fscanf(fp, "%s", storageArray);
}
...
/* file close code */

如何调整我的代码,以便不再将每个单独的字符打印到屏幕上,而是得到如下所示的行为:(注意:在我的程序中,我假设用户输入一行包含三个字符。)

INPUT FILE:
a b c
f e d

LINE STRUCT 1:
char1 = a
char2 = b
char3 = c
LINE STRUCT 2:
char1 = f
char2 = e
char3 = d

我觉得解决方案可能涉及类似于我编写的 while 的嵌套循环,其中外部循环跟踪行,内部循环跟踪字符。

最佳答案

或者试试这个:

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

#define READ_OPTIONS "r"

struct line {
char char1;
char char2;
char char3;

struct line* next;
};

struct line* g_lines = NULL;


int main(int argc, char** argv) {
char buf[8] = {0};
struct line* newline, *iter, *head;
int counter = 1;

FILE* fp = fopen("file.txt", READ_OPTIONS);

if(NULL != fp) {
while(fgets(buf, 8, fp)) {
newline = malloc(sizeof(struct line));
if(NULL != newline) {
memset(newline, 0, sizeof(struct line));
sscanf(buf, "%c %c %c",
&newline->char1,
&newline->char2,
&newline->char3);

if(NULL != g_lines) {
for(iter = g_lines;
NULL != iter->next;
iter = iter->next);

iter->next = newline;

} else g_lines = newline;
}
}
fclose(fp);
} else return -1;


/* print the contents */
for(iter = g_lines;
NULL != iter;
iter = iter->next,
++counter)
printf("Line %d: char1=%c char2=%c char3=%c\n",
counter, iter->char1, iter->char2,
iter->char3);


/*
now to free memory before returning
control to the operating system
*/
for(iter = g_lines;
NULL != iter;)
{
head = iter->next;
free(iter);
iter = head;
}
return 0;
}

关于C - 将输入文件解析为行和字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22123946/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com