0

I'm trying to get my code to read in a txt file, it was working yesterday but now when I run it through "start without debugging" it prints out the message I prompted it to but that's it, and no matter what I type in it re-asks the user the same question instead of printing what was written in the txt file.

#include <iostream>
#include <fstream>
#include <cmath>
#include <cstdlib>

void main ()
{
    FILE *file_in;
    char value;
    file_in = NULL;
    char unencrypted [1000];

    while (file_in == NULL)
    {
        printf("Please enter the name of the file you want to open:\n");
        scanf("%s", unencrypted);
        file_in = fopen(unencrypted, "r");
    }

    printf("\n This file consists of the following message: \n");
    while(!feof(file_in))
    {
        value = fgetc(file_in);
        printf("%c", value);
    }

    fclose(file_in);
}
Tim Pierce
  • 5,514
  • 1
  • 15
  • 31
  • 1
    Why on earth are you using both `` and `` ? And using C style in `C++` ? – P0W Dec 08 '13 at 16:49
  • 1
    You should be able to use the errno variable to get more information. Add a line to print the errno whenever fopen returns null, and that should help you debug this. – user1612868 Dec 08 '13 at 16:54
  • Read this “while( !feof( file ) )” is always wrong" - http://stackoverflow.com/questions/5431941/while-feof-file-is-always-wrong – SChepurin Dec 08 '13 at 16:55
  • You should return an error code to the operating system by correctly defining `main` as `int main`. – Thomas Matthews Dec 08 '13 at 17:12

2 Answers2

1

If it repeatedly asks the user to enter a file name, that means that fopen is returning NULL. You should find out why:

file_in = fopen(unencrypted, "r");
if (file_in == NULL)
    perror(unencrypted);
Tim Pierce
  • 5,514
  • 1
  • 15
  • 31
0

I don't know what platform you are on, but IDEs typically build release and debug builds to different folders. If you put your test text file in the debug folder, and then do a release build, the file will be unreachable with a relative path.