c - 我不知道如何将输入文件中的字符串(单词)读取到链接列表中

标签 c

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


struct node
{
  char *data;
  struct node *next;
};


void insertNode(struct node**, char *);
void printList(struct node*);


int main()
{
  struct node *head = NULL;
  FILE *fptr;
  char file_name[20];
  char str[1000];
  int numOfChar;


  printf("Enter the name of the file: ");
  scanf("%s",file_name);


  printf("Enter the number of characters per line: ");
  scanf("%d",&numOfChar);


  fptr=fopen(file_name,"r");
    char tokens[100];
  while(fgets(str, sizeof(str), fptr) != NULL)
  {

    while (sscanf(str, "%s", tokens) != EOF)
    {

    }


  }


  fclose(fptr);
  printList(head);


  return 0;
}


void insertNode(struct node** nodeHead, char *data)
{
    struct node* new_node = (struct node*) malloc(sizeof(struct node));
    struct node *last = *nodeHead;
    char *str;


    str= (char *)malloc(60*sizeof(char));
    strcpy(str, data);


    new_node->data  = str;
    new_node->next = NULL;


    if (*nodeHead == NULL)
    {
       *nodeHead = new_node;
       return;
    }


    while (last->next != NULL)
    {
        last = last->next;
    }


    last->next = new_node;
}

我的程序应该将每个单词读入链接列表,但我不知道如何从输入文件中获取每个单词/字符串。输入文件是 ASCII 文本文件。有什么建议么?感谢您的帮助。

void printList(struct node* node)
{
    while(node != NULL)
    {
        printf(" %s ", node->data);
        node = node->next;
    }
}

最佳答案

例如,您可以使用非常低级别的字符扫描,如下例所示 - 它可能会扩展为实际接受多个分隔符字符、分隔符重复等:

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

int main() {
  FILE *fptr;
  char buf[100];
  char *p, *s;

  strcpy(buf, "this is just a test");

  fptr=fopen("test.txt","r");
  while(fgets(buf, sizeof(buf), fptr) != NULL)
  {
    printf("LINE: %s\n", buf);
    /* scan characters and print tokens - single space is a separator */
    p = s = buf;
    while(*p!=0) {
      if (*p==' ') {
        *p = 0;
        printf("TOKEN: %s\n", s);
        s = p+1;
      }
      p++;
    }
    printf("TOKEN: %s\n", s);

  }


  fclose(fptr);
  return 0;
}

调用可能如下所示:

$ cat test.txt
this is test1
this is test2
$ gcc tokens.c && ./a.out
LINE: this is test1

TOKEN: this
TOKEN: is
TOKEN: test1

LINE: this is test2

TOKEN: this
TOKEN: is
TOKEN: test2

关于c - 我不知道如何将输入文件中的字符串(单词)读取到链接列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36107540/

相关文章:

c - 如果程序在 2 秒内执行 n=10,执行 n=100 需要多少时间?

C: 分配给 char... 期待类型转换?

c - 马氏距离反转协方差矩阵

c - 是什么导致了这个段错误?

c - 使用 SIMD,如何将 8 位掩码扩展为 16 位掩码?

c - 程序没有在 scanf ("%c", &ch) 行停止,为什么?

c++ - C/C++ : Automatically initialize pointers to null in visual studio

c - 将文件路径从数组传递给 fopen 在 C 中失败

我可以在没有 atomic_load 的情况下读取原子变量吗?

c - 从 stdin 读取 execv 的参数? (C)