C编程。文件 I/O、链接列表和结构

标签 c parsing struct io

我的作业要求我编辑提供给我的 C 程序,以便它可以从文本文档中读取,其中每一行如下所示:

int%char%char%Double%int%int%int

在文件末尾有任意行数和一个空行。

这个文本文件被传递给这个程序:

#include <stdlib.h> 
#include <stdio.h> 
struct node{  
  int element; 
  struct node * next;
}; 
// node structure 
struct node * head = NULL; // head node
void add_node(int num) {
  if (head == NULL){
    head = (struct node *) malloc(sizeof(struct node));
    head->element = num;
  }
  else{
    struct node * p = head;
    while(p->next != NULL)
    p = p->next;
    p->next = (struct node *) malloc(sizeof(struct node));
    p->next->element = num;
  }
 }
void print_list() {
  struct node * p = head;
  while(p != NULL){
    printf("%d ", p->element);
    p = p->next;
  }
 } 
void free_list() {
  struct node * p = head;
  while(head != NULL){
    p = head->next;
    free(head);
    head = p;
  }
 }
int main(int argc, char const *argv[]) {
  int n, i;
  for (i = 0; i < 10; i++) {
    scanf("%d", &n);
    add_node(n);
  }
  print_list();
  free_list();
  return 0;
 }

我需要编辑此程序以将文件中的 7 个字段(ID、类别、详细信息、金额、年、月、日)包含在结构节点中。然后让它从文本文件(现在是 File_name.txt)中读取,在结构节点中添加它们之间没有 % 分隔符的字段,然后按这样的顺序打印出来(RecordID: (ID) Category: (category) Amount : $(amount) Date: (Month)-(Day)-(Year) Detail: (detail)) 并在程序终止前释放所有指针。我不希望你们都为我做作业,只是我不知道 C 编程是如何工作的,我需要这样做,所以如果有人能帮助我指出正确的方向,告诉我如何去做这件事不胜感激。

最佳答案

据我所见。

  • 您将不得不使用文件中的指定变量创建您自己的结构。

  • 读取每一行并智能地解析它们...函数 strtok 应该能够在 C 中执行此操作。

  • 使用不应该太难编写的函数提取变量以存储在创建的结构

  • 其余的您可以或应该能够处理

这可能没有你希望的那么有用,但你可以试着让我理解,这样我可以帮助做得更好

关于C编程。文件 I/O、链接列表和结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36803055/

相关文章:

php - 将脚本从 C 迁移到 PHP

c - 在 C "left operand must be l-value"中解析字符串时出错

c - 为什么指针 + 1 实际上加 4

javascript - JSON从php解析javascript中的数据

c - 我如何更正这个程序(结构和指针(?))?

c - 68HC11 上使用 4 字节数字的斐波那契数列

excel - 按月在美国所有州的 Excel 中获得最高排名的最简单方法?

javascript - YouTube 使用 JavaScript 和 jQuery 将 url 替换为视频 ID

c - 如何在C中实现二维结构数组

amazon-web-services - 即使存在也缺少 key