1

My script in C++ give me this result without any errors:

1 2 Press any key to continue...

This is my program:

    const char* fileName = "kwerendy.txt";
    FILE * file = fopen(fileName, "r");
    while (! feof(file))
    {
        printf("1\n");
        char* row;
        printf("2\n");
        fgets(row, 1000, file);
        printf("3\n");
        int i = 0;
        printf("4\n");
        cout << "TEXT (line[" << i << "]): " << row;
    }

Have you any ideas, because I don't know how to repair this.

Andaar
  • 11
  • 2
  • `row` doesn't point to anything, you're not writing to a valid location. And why are you using `printf` and `fopen` with C++? – Greg Kikola Jan 27 '17 at 03:28
  • I used printf only for testing how it work's and fopen, because I' m prescribing code from php. If I put equal sign after row (something like this: row = fgets) my code result is 1 after this program stops. – Andaar Jan 27 '17 at 03:36
  • Maybe I don't understand how C++ works :/ Here is my program in C++: https://hastebin.com/xovimuxiwa.cpp And here in PHP: https://hastebin.com/uyepazowaq.xml – Andaar Jan 27 '17 at 03:37
  • don't use feof in a loop condition (especially not in C++ but I don't think it's a good idea in other languages either) – M.M Jan 27 '17 at 07:06
  • @M.M Could you write me why this isn't a good practice? What are the consequences using this in c++? – Andaar Jan 28 '17 at 10:02
  • see http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong and http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong – M.M Jan 28 '17 at 20:04

1 Answers1

2

row is not assigned a value, so you are writing to an arbitrary memory address--that's very bad. It's undefined behavior and even if it works now it is likely to fail in the future. You need to allocate space for the characters that fgets reads. Or you could declare row as a static array:

char row[buffer_size];
fgets(row, buffer_size, file);

A better way would be to use an ifstream with strings:

std::ifstream file(fileName);
std::string line;
int i = 0;
while (getline(file, line)) {
    std::cout << "TEXT (line[" << i++ << "]): "
              << line << std::endl;
}
Greg Kikola
  • 573
  • 3
  • 6
  • Thanks and last question. How can I use string type of value, because I don't get it? When I change char to string I've an error that says I can not convert char to string value: "error: cannot convert 'std::string* {aka std::basic_string*}' to 'char*' for argument '1' to 'char* fgets(char*, int, FILE*)' fgets(row, 100, file);" – Andaar Jan 27 '17 at 03:56
  • I edited my answer to show an example of how to do it the C++ way, see above. – Greg Kikola Jan 27 '17 at 04:01
  • Thank you so much. – Andaar Jan 27 '17 at 04:05