Hey All,

I have stumbled upon a small problem while using an fgets function. I need to make a program that reads in lines from a text file (text file is entered via command line)

Here is a little snippet of the code (concerning only the fgets function :P)

void loadText(list<char> &listId, char *file);


int main(int argc, char *argv[])
{
list<char> listId;
loadText(listId, argv[1]);

return 0;
}

void loadText(list<char> &listId, char *file)
{
   ifstream fin;
   fin.open(file);
   char mystring[100];
   
   while(fin >> mystring)
   {
       fgets (mystring, 100, file);
   }
   fin.close();
}

Now when I compile this I get an error:
"error cannot convert 'char*' to 'FILE*' for argument '3' to 'char* fgets(char*, int, FILE*)"

I try then to call fgets by the address of file i.e.

fgets (mystring, 100, &file);

Then I get the following error:

Now when I compile this I get an error:
"error cannot convert 'char**' to 'FILE*' for argument '3' to 'char* fgets(char*, int, FILE*)"

I have scoured the great interwebs for a similar problem and in one of the solutions the person called the &file and it worked but he did not have to use the command argument for a file (instead the file was inputed via cin)

Any thoughts?

char *file?

If you're using fgets(), I'm guessing it wants a C-style FILE *. ;)

Anyway, you're in C++ land now, try getline() or something like that. Safer, easier.

Other then that, the code is kinda.. bad..

You've a loop that fetches data from the ifstream into your char array, which is okay, but why do you want to read into that char array again in the loop?

>> fgets (mystring, 100, &file);
That's wrong -- remove the & symbol

int main(int argc, char* argv[])
{
    char line[255];
    FILE* fp;
    if( argc == 1)
        fp = fopen(argv[1], "r");
   else
       fp = fopen ("myfile.txt", "r");
  
   while( fgets( line, sizeof(line), fp) != NULL)
   {
        printf("%s", line);
   }
   fclose(fp);
}

Ancient, even then it's wrong, file is a char pointer.

void loadText(list<char> &listId, char *file) //<----
{
   ifstream fin;
   fin.open(file);
   char mystring[100];
   
   while(fin >> mystring)
   {
       fgets (mystring, 100, file); //<-- fgets(char *, 100, char*)? xD
   }
   fin.close();
}

Ancient, even then it's wrong, file is a char pointer.

That was the whole point -- its supposed to be FILE*, not char*

Thank you for the replies gentlemen, I was advised to check the fgets() function by the lecturer but it seems he only wanted to point out the "read in by line" clue as fgets() does.

I will instead try and use getline() function when I get home :)

quick addition,

I decided to write some classes for my code which created a further amount of headaches to fix so the getline() problem will have to wait :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.