我有一些问题从C中的.txt文件中读取单词

时间:2014-05-24 17:25:34

标签: c file scanf

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

#define WORD_LENGHT 30

typedef struct numnode
{
    char* dataPtr;
    struct numnode* next;

} NUMNODE;

typedef struct num
{
   NUMNODE* head;

} NUM;
//////
//////
//////
int main()
{
    char *wp;
    char word[80];
    int total=0;
    FILE *test= fopen("book.txt", "r");
    while (fscanf (test, "%s",word) == 1)
    {
        //printf("%s\n",word);  //counting how many words in a book.txt
        total++;
    }

    if (total==0)
    {
        printf("File not found\n"); //if no word, then return
        return;
    }

    NUM* dic;
    dic=(NUM*)malloc(sizeof(NUM)*total);
    NUMNODE* temp;
    temp=dic->head;

    FILE*file = fopen("book.txt", "r");
    while(!feof(file))
    {
        wp=malloc(100);  
        printf("test1\n");
        fscanf(file,"%s",wp);
        strcpy(temp->dataPtr,wp);  //strcpy is the error part 
        printf("test2\n");
        temp=temp->next;
    }
    return;
}
  

这个c代码逐字逐句地从book.txt中读取并将它们链接起来   名单。我有一些问题!feof(文件)part.Couldnt弄清楚是什么   to do.i认为这循环中的strcpy是这个问题的原因   等待你的帮助:3

2 个答案:

答案 0 :(得分:0)

错误是因为struct member dataPtr是一个指针,而不是一个数组。所以strcpy来电

strcpy(temp->dataPtr,wp);

是错误的,因为它访问非法内存调用未定义的行为。你需要的是

typedef struct numnode
{
    char dataPtr[100];  // dataPtr changed to an array type
    struct numnode* next;

} NUMNODE;

请注意,dataPtr必须至少是wp指向的缓冲区的大小。

答案 1 :(得分:-1)

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

#define WORD_LENGHT 30

typedef struct numnode {
    char* dataPtr;
    struct numnode* next;
} NUMNODE;

typedef struct num {
   NUMNODE* head;
} NUM;

int main(){
    NUM dic = { NULL };
    char word[WORD_LENGHT];
    int total=0;//num of word
    FILE *file= fopen("book.txt", "r");
    NUMNODE *curr = NULL, *temp;

    while (fscanf(file, "%29s", word) == 1) {
        temp = malloc(sizeof(*temp));
        temp->dataPtr = malloc(strlen(word) + 1);
        temp->next = NULL;,
        strcpy(temp->dataPtr, word);
        if(curr){
            curr = curr->next = temp;
        } else {
            dic.head = curr = temp;
        }
        ++total;
    }

    if (total==0){
        printf("File does not has word\n");
        return;
    }

    //test print
    printf("%d\n", total);
    if(total>1){
        printf("%s\n", dic.head->dataPtr);
        printf("%s\n", dic.head->next->dataPtr);
    }
    //do something
    return;
}