Reputation: 11
Whenever I try to make a program based on files, my program is never able to open the file itself.
It always ends up executing the part of the program in the "else" part. Is it because my file might not be in the same directory? If so, how do I find the location of my file? Here's the code. I just wanted to check if its working fine or not by inputting and outputting the strings using the concept of files.
int main()
{
char str1[20], str2[20];
FILE *pFile;
pFile = fopen("Rocket.txt", "r+");
if (pFile != NULL) {
while (feof(pFile)) {
cout << "Enter String 1: " << endl;
fgets(str1, 20, pFile);
cout << "Enter String 2: " << endl;
fgets(str2, 20, pFile);
cout << "The Strings input are: " << endl;
fputs(str1, pFile);
fputs(str2, pFile);
}
}
else {
cout << "File not opened." << endl;
}
Upvotes: 1
Views: 81
Reputation: 28
1) "How do I find the location of my file?"
For example if it was C:\Users\user\Desktop
then the location you write is c:\\Users\\user\\Desktop\\Rocket.txt
2) In your code, I found two bugs
Notice that in the "while condition" you should write (feof(pFile)==0)
or (!feof(pFile))
because it should continue reading from file until it reaches the end of file and feof(pFile) == 1
.
"puts" writes at the end of the file. So when the file marker is not at the end of the file, it doesn't write on it, unless your initial file has just 37 characters. So it's not a good idea to use "puts" in this program. Instead , you can use cout
to check out values of str1
and str2
.
Upvotes: 1