gpt4 book ai didi

c - 在文本文件 C 中最多读取两行时出现问题

转载 作者:太空宇宙 更新时间:2023-11-04 04:15:33 28 4
gpt4 key购买 nike

我无法从文本文件中读取特定数量的单词。到目前为止,我的程序从一个文本文件中读取两个字符串,并将其存储在一个链表中。但是,从文本文件中读取的值应该是:

(命令)(值)

按照这个顺序,仅此而已。如果我添加一个额外的命令或值,它将将该字符串存储在列表的下一个节点中,并将所有内容移动一个。我的问题是我找不到一种方法来对文本文件中同一行的额外命令进行错误检查。我最初的想法是只读取前两个字符串并忽略行中的任何其他内容。如果还有其他方法可以解决此问题,请告诉我。感谢任何改进我的代码的帮助!

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


/*This typedefs a struct...*/
typedef struct LinkedListNode
{
char* commandstring;
char* valuestring;
char valueint;
struct LinkedListNode *next;
}LINKEDLISTNODE;


int main (int argc, char *argv[])
{
FILE* fp;
LINKEDLISTNODE *current, *head, *temp;

int integer_check;

head = NULL;
current = head;


fp = fopen (argv[1], "r");


/*This will set a buffer to find the maximum length we need for the buffer. The max length will be the length of the longest line in the text file.*/
fseek(fp,0, SEEK_END);
long filesize = ftell(fp);
fseek(fp, 0, SEEK_SET);
char* buffer = malloc(filesize + 1);

char tempCommand[filesize];
char tempValue[filesize];


/*Initialise linked list with the same amount of nodes that the text file has lines*/
while(fgets(buffer, filesize, fp) != NULL)
{
LINKEDLISTNODE* node = malloc(sizeof(LINKEDLISTNODE));
node->commandstring = (char*)malloc(sizeof(char)*8);
node->valuestring = (char*)malloc(sizeof(char)*5);
node->next = NULL;

if (head == NULL)
{
head = node;
current = head;
}
else
{
current->next = node;
current = current->next;
}
}



/*Allocate the command string to the command field and the value string to the value field:*/
current = head;
rewind(fp);
while(current != NULL)
{
fscanf(fp, "%s %s\n", current->commandstring, current->valuestring);
current = current->next;
}


/*Print the list to make sure the strings are set correctly in the fields*/
current = head;
rewind(fp);
while(current != NULL)
{
printf("node[%p]:[%s],[%s] \n", current->commandstring, current->commandstring, current->valuestring);
current = current->next;
}
/*Free each node:*/
current = head;
while(current != NULL)
{
temp = current->next;
current = temp;
}

free(head);
free(temp);
free(current);
fclose (fp);

return (0);
}

最佳答案

您可以在同一个循环中分配空间并传递您的值。您可以使用 strtok 获取字符串,直到第一次出现空间,然后使用 strdup 分配空间并同时分配值。所以现在,如果您在同一行上有多个(命令)(值),它将被添加。

while(fgets(buffer, filesize, fp) != NULL) {

char * command = strtok(buffer, " \n");
char * value = NULL;

while ((value = strtok(NULL, " \n")) != NULL) {

LINKEDLISTNODE* node = malloc(sizeof(LINKEDLISTNODE));

node->commandstring = strdup(command);
node->valuestring = strdup(value);
node->next = NULL;

if (head == NULL) {

head = node;
current = head;
}

else {

current->next = node;
current = current->next;
}

command = strtok(NULL, " \n");
}
}

关于c - 在文本文件 C 中最多读取两行时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52800505/

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