0

Recently I've started to learn C and I'm confused by this thing here ->

I had a program in Java which was reading a file and counting words in it. Now I'm trying to re-write it in C.

So, in Java I had this:

class with main() method

...
File words = new File("AV1611Bible.txt");
WordReader wr = new WordReader(words);
...

and next to the constructor in the WR class

   private static final int READING_WHITESPACE = 11;
   ...

   private int state;
   private BufferedReader reader;

   public WordReader(File words)
   {
      state = READING_WHITESPACE;
      try
      {
         reader = new BufferedReader(new FileReader(words));
      }
      catch (FileNotFoundException e)
      {
      }
   }

Everything is initialized and can be used.

Now in C it is:

(main class)

     ...
     FILE* file;
     char* fileToRead = "toRead.txt";
     file = fopen(fileToRead, "r");

     WordReader* reader = createWordReader(file);
     ...

Now what confuses me is what exactly I need to do with this FILE object in the WR constructor.

(header file for WR)

typedef struct _WordReader
{
   int state;
   FILE* file;
} WordReader;

WordReader* createWordReader(FILE* fileToRead);
...

(WordReader.c)

    WordReader* createWordReader(FILE* fileToRead)
    {
            WordReader* reader = malloc(sizeof(WordReader));
            reader -> state = READING_WHITESPACE;
            //-----------------
            reader -> file; // What to do with it?
            //-----------------
            // reader -> file = fopen(fileToRead, "r"); Maybe? I've tried like this but   
all I get is a bunch of errors.
            //-----------------
       return reader;
    }
4

2 回答 2

1

In your main class, you already used fopen to get a file handle for the file you want to read from, and you passed it as an argument to createWordReader. You probably just want to save the file handle in the WordReader struct, so that you can use it in future calls to fread when you want to read data from the file.

reader->file = fileToRead;
于 2013-09-21T19:12:14.847 回答
0

I think you're looking for this:

reader -> file = fileToRead;
于 2013-09-21T19:15:28.187 回答