2017-04-22 88 views
1

我非常需要一些教授給我的練習。從本質上講,我使用一個結構和動態內存來編寫一個程序,在這個程序中它將讀取一個文件,每行有一個單詞,並且它將打印到一個新文件中的每個獨特單詞以及它在文件中的次數。從文件中讀取動態內存

因此,舉例來說,如果該文件將在有這個

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文件中存儲文件中的一個單詞,然後在該數組中增加count。我不知道如何去將這個單詞存儲在*單詞中。任何幫助將不勝感激

+1

你必須爲'字符*臨時分配內存;'你在使用它之前'fscanf' –

+0

1 )int main(){' - >'int main(int argc,char * argv []){','from = fopen(「argc [1]」,「r」); to = fopen(「argv [1]」,「w」);' - >'from = fopen(argv [1],「r」); to = fopen(argv [2],「w」);' – BLUEPIXY

+0

@BLUEPIXY他首先必須重新定義man,然後是'main(int argc,char * argv [])' –

回答

-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");