1

I desperately need some help with an exercise my professor gave me. Essentially, I'm making a program using a structure and dynamic memory where it'll read a file where each line has one word, and it'll print to a new file each unique word and how many times it was in the file.

So for instance, if the file going in had this

apple
orange
orange

The file it prints to would say

apple 1
orange 2

So far, this is my code

#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 should store a word from the file in the wordfreq file, then increment count in that array. I have no clue how to go about storing the word in *word though. Any help would be greatly appreciated

Sawyer Kim
  • 13
  • 3
  • 1
    You have to allocate memory for `char *temp;` before you use it in `fscanf` – Seek Addo Apr 22 '17 at 02:33
  • 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 Apr 22 '17 at 02:35
  • @BLUEPIXY he first has to redefine man before that is `main(int argc, char *argv[])` – Seek Addo Apr 22 '17 at 02:37
  • You may find [**Count the reocurrence of words in text file**](http://stackoverflow.com/questions/43444995/count-the-reocurrence-of-words-in-text-file/43445812#43445812) helpful. – David C. Rankin Apr 22 '17 at 05:26

1 Answers1

-1

This is how in general your read/write from a file

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");
BlooB
  • 955
  • 10
  • 23