从文件

时间:2017-04-22 02:31:13

标签: c memory-management struct

我迫切需要一些教授给我的练习帮助。本质上,我正在使用一个结构和动态内存来创建一个程序,它将读取一个文件,其中每行有一个单词,并且它将打印到一个新文件中的每个唯一单词以及它在文件中的次数。

例如,如果进入的文件有这个

apple
orange
orange

它打印的文件会说

apple 1
orange 2

到目前为止,这是我的代码

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

struct wordfreq {
int count;
char *word;
};

int main(int argc, char *argv[]){

int i;
char *temp;
FILE *from, *to;
from = fopen("argc[1]","r");
to = fopen("argv[1]","w");

struct wordfreq w1[1000];
struct wordfreq *w1ptr[1000];
for(i = 0; i < 1000; i++)
    w1ptr[i] = NULL;
for(i = 0; i < 1000; i++)
    w1ptr[i] = (struct wordfreq*)malloc(sizeof(struct wordfreq));

while(fscanf(from,"%256s",temp)>0){

}

for(i = 999; i >= 0; i--)
    free(w1ptr[i]);

}

w1ptr应该在wordfreq文件中存储文件中的单词,然后在该数组中增加计数。我不知道如何将单词存储在* word中。任何帮助将不胜感激

1 个答案:

答案 0 :(得分:-1)

这是一般的文件读/写方式

const int maxString = 1024; // put this before the main

    const char * fn = "test.file";          // file name
    const char * str = "This is a literal C-string.\n";

    // create/write the file
    puts("writing file\n");
    FILE * fw = fopen(fn, "w");
    for(int i = 0; i < 5; i++) {
        fputs(str, fw);
    }

    fclose(fw);
    puts("done.");

    // read the file
    printf("reading file\n");
    char buf[maxString];
    FILE * fr = fopen(fn, "r");
    while(fgets(buf, maxString, fr)) {
        fputs(buf, stdout);
    }

    fclose(fr);
    remove(fn); // to delete a file

    puts("done.\n");
相关问题