Hello all, I wanna check if a file contains the word "Permitted".
Unfortunately I don;t know very well how to use fopen. Can you help me a bit? Thank you! Let as take for example that the file is at
/home/alex/file.txt
1. #include <stdio.h>
2. #include <cerrno>
3. #include <sys/stat.h>
4. #include <sys/types.h>
5. #include <pwd.h>
6. #include <unistd.h>
7. #include <string>
8. #include <iostream>
9. usingnamespace std;
10. int main()
11. {
12. struct passwd *passwd;
13. passwd = getpwuid ( getuid());
14. string user(passwd->pw_name);
15. user = "/home/" + user + "/.config/Home/unkilled.txt";
16. ifstream file( user );
17.
18. string temp;
19.
20. //Get file contents line by line
21. while(getline(user,temp)){
22. //Check if "Permitted" is in current string
23. if(temp.find("permitted",0) != string::npos){
24. cout<<"Permitted!";
25. }
26. else{
27. cout<<"Not Permitted!";
28. }
29. }
30. file.close;
31.
32. return 0;
33. }
but I get 2 errors:
1 2
1) /home/alex/Qt/check/main.cpp:line 16: error: variable ‘std::ifstream file’ has initializer but incomplete type
2) /home/alex/Qt/check/main.cpp:line 21: error: cannot convert ‘std::string’ to ‘char**’ for argument ‘1’ to ‘__ssize_t getline(char**, size_t*, FILE*)’
To fix the first error, You need to #include <fstream>
Line 21: You are trying to read contents of string, not a file. So line 21 must be like this while(getline(file,temp)){
Hope this helps.
its good to refer any library reference document first which will help you to understand things more clearly than firing such a question directly to a forum and get answer to a particular problem.
ifstream constructor takes a const char* as the first argument
Oops I forgot that (BTW in C++0x standard fstream constructor will take both const char* and std::string)
One more error: you forgot brackets in line 30 --> file.close();
There are two versions of getline(). The one he is using takes a string rather than a char array.
Thanks for the information. I was unaware about the getline() defined in string.h .
istream has following versions of getline().
1 2
istream& getline (char* s, streamsize n );
istream& getline (char* s, streamsize n, char delim );
and string.h has following versions
1 2
istream& getline ( istream& is, string& str, char delim );
istream& getline ( istream& is, string& str );
If you are intended to use the version which uses a string instead of char array, then the first argument should be the input stream. Here it should be "file".
So line number 21 should be
while(getline(file,temp)){
I came to know that another version of getline() is also available which is defined in stdio.h as part of GNU extensions and are available in libc 4.6.27 onwards. Its signature is