1

I'm trying to read the file named by argv[1], but I have no idea on how I go about doing this. It feels like it's something simple, the error message I'm getting when compiling is,

main.cpp: In function ‘void* ReadFile(char**, int&)’:
main.cpp:43:22: error: request for member ‘c_str’ in ‘*(argv + 8u)’, which is of non-class type ‘char*’
make: *** [main.o] Error 1

This is my code:

#include "movies.h"
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;

void *ReadFile(char*[], int&);
int size;
int main(int argc, char *argv[])
{   
    char * title[100];

    cout << argv[1] << endl;
    //strcpy(argv[1],title[100]);
    //cout << title << endl;
    ReadFile(argv , size);

    return 0;
}

void *ReadFile(char * argv[] , int& size)
{
    char data;
    //char title[50];
    //strcpy(title,argv[1]);
    //cout << title << endl;
    ifstream fin;
    fin.open(argv[1].c_str()); //filename

    if (fin.good())
    {
        fin >> data;       
        cout << data << " ";                      
        while (!fin.eof( ))      
        {
            fin >> data; 
            cout << data << " ";               
        }
    }  
}
Deduplicator
  • 44,692
  • 7
  • 66
  • 118
Impulse
  • 155
  • 11
  • 2
    [`c_str()`](http://en.cppreference.com/w/cpp/string/basic_string/c_str) is a method of the `std::string` class. `char` has no methods at all! – πάντα ῥεῖ Jun 05 '14 at 15:18
  • 1
    Exactly the same question, even has the text `argv[1].c_str()` in it: [Why should I use c\_str() in functions](http://stackoverflow.com/questions/6396330/why-should-i-use-c-str-in-functions) – Csq Jun 05 '14 at 15:21
  • Anyway, why is `size` a global, and why do you pass all program arguments to `ReadFile`, instead of only the filename? – Deduplicator Jun 05 '14 at 15:23

2 Answers2

5

As the error says, you're trying to call a member function c_str() on a non-class type. argv[1] is a pointer to an array of characters (a C-style string), not a class object.

Simply pass that pointer to open():

fin.open(argv[1]);

You would call c_str() on a std::string object, if you had one of those but needed a C-style string. (Historically, you'd have to do that to call fin.open() if you had std::string; but since C++11, you can pass that type directly).

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
3

The .c_str() function is something that is defined for string objects to convert it into a char *. You are trying to use it on a char *. Instead, use fin.open(argv[1]), as it is already a C string.

wolfPack88
  • 4,163
  • 4
  • 32
  • 47