#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;
}
}
答案 0 :(得分:0)
例如,您可以使用非常低级别的字符扫描,如下例所示 - 它可能会扩展为实际接受多个分隔符,分隔符重复等。:
#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
答案 1 :(得分:0)
#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");
while(fscanf(fptr, "%s ", str) != EOF)
{
insertNode(&head, str);
}
fclose(fptr);
printList(head);
return 0;
}
void insertNode(struct node** nodeHead, char *data)
{
struct node* new_node = malloc(sizeof *new_node);
new_node->data = strdup(data);
new_node->next = NULL;
while (*nodeHead)
nodeHead = &(*nodeHead)->next;
*nodeHead = new_node;
}
void printList(struct node* node)
{
while(node != NULL)
{
printf(" %s ", node->data);
node = node->next;
}
}