My files are never opening? - c++

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;
}

1) "How do I find the location of my file?"
right-click on your file
properties->Details->Folder path or
properties->General->Location
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.

Related

How to search and use a file in ssh/server

My c++ program is being run on xCode. One part of my program is searching for a file that's on my computer and using it to store the values into an array. Everything is working just fine on xCode, but when I moved my files .cpp .h .txt into a server or ssh it doesn't seem to be working.
This is a snippet of my code:
case 'W':
if(heap.capacity == 0)
cout<< "Sorry!!! It cannot be done. Please initialize the heap first.";
else{
file.open("/Users/mbojo/Downloads/HEAPinput2.txt");
int line;
int count = 0;
while(file>>line)
count++;
file.close();
heap.capacity = count;
cout<< "COMMAND: " << choice << "\n" << "The capacity is "<<
heap.capacity << "\nSize is " << heap.size<<endl;
}
break;
Is there anything I need to change in ssh/server that can read the file.

C++ deleting a line of text from .txt file by first word

What my program needs to do is delete a line of text from .txt file but it needs to do so with user input. User says which line he wants to delete by typing first word and my program should delete the whole line eg.
Image with example .txt file
User types opel and it should delete the line opel (astra).
string izbrisiLiniju;
string linija;
ifstream citanjeLinija;
citanjeLinija.open("auti.txt");
ofstream brisanjeLinija;
brisanjeLinija.open("temp.txt");
cout << "Ispis autiju" << endl;
while (getline(citanjeLinija, linija))
{
cout << linija << endl;
}
cout << "Unesite vrstu automobila za izbrisati: " << endl;
getline(cin, izbrisiLiniju);
while (getline(citanjeLinija, linija))
{
if (linija != izbrisiLiniju)
{
brisanjeLinija << linija << '\n';
}
}
brisanjeLinija.close();
citanjeLinija.close();
remove("auti.txt");
rename("temp.txt", "auti.txt");
getchar();
Here is how i tried doing it but for some reason it just deletes every line.
Thank you in advance.
You have a few bugs.
You compare the entire string, not just the prefix.
Replace linija != izbrisiLiniju with linija.compare(0, izbrisiLiniju.size(), izbrisiLiniju) == 0

File won't open for ifstream [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Hi my professor posted this example to her website giving an example of ifstreams, how come I cant open any .txt file?
#include <iostream>
#include <iomanip> // for setw
#include <fstream> // for ifstream, ofstream
using namespace std;
int main()
{
char filename[25]; // a string for filename entry
int val; // for reading integers from file
int sum = 0, count = 0;
double average;
ifstream in1; // create an input file stream
do
{
in1.clear();
cout << "Please enter the name of the input file.\n";
cout << "Filename: ";
cin >> setw(25) >> filename;
in1.open(filename);
if (!in1)
cout << "That is not a valid file. Try again!\n";
} while (!in1);
// PROCESS THE INPUT FILE
// Read all integer values and compute average
while (!in1.eof()) // while not end of file
{
in1 >> val; // read an integer from file
if (!in1.fail()) // in case last call failed to read an int
{ // due to trailing white space at end of file
count++;
sum += val;
}
}
average = static_cast<double>(sum) / count;
cout << "There were " << count << " numbers in the file\n";
cout << "Sum = " << sum << "\t\tAverage = " << average << "\n\n";
in1.close();
return 0;
}
This is extremely aggravating! Is it a problem with my computer or something?
Blockquote
Let me make two assumptions: you are using some IDE and you are using relative paths.
IDEs often execute your binary from a directory different than the project main dir. Try using absolute paths, find the right directory or run the file yourself.
The first thing you should start do do, is to write code to understand the error. It's not only for you now, to debug, but also for users later on when they will encounter problems:
....
if (!in1) { // replace this bloc
cout << filename << " is not a valid file\n"; // print filename to find out any issues (truncated name, etc...)
cout << "Error code: " << strerror(errno)<<endl; // Get some system info as to why
char cwd[512]; // print current working directory.
getcwd(cwd, sizeof(cwd)); // in case your path is relative
cout << "Current directory is " << cwd << endl;
cout << "Try again !\n";
}
Please note that getcwd() works as under linux, but in windows, you'll have to use _getcwd() instead.
IMPORTANT REMARK:
The following is not causing your error, but it might cause problems later on:
while (!in1.eof()) { // while not end of file
in1 >> val; // read an integer from file
...
prefer the following:
while (in1 >> val) { // while read of file works
...
Browse arround on SO: there are lots of questions/answers that explain why.

strcmp() function does not compare properly against user input and struct file data

I'm trying to solve this issue where when i try and search for a certain module name in my .dat file, it doesn't show the info of some module like module name, module code.
Example: if I search CSCI124, it shows all of the needed info i need in the output.
However if i try searching for CSCI114 or MATH121, it doesn't show any info except for "Subject Code not found.."
I have tried playing around with not putting in the while loop however it doesn't work as well.
It would be awesome if you guys could help me out, just started learning about c++
Subject subjectDB;
char subCode[MAX];
int printOnce = 0;
int position = 0;
cout << "Enter Subject Code: ";
cin >> subCode;
// Open binary file
ifstream fin("Subject.dat", ios::out | ios::binary);
if (!fin)
{
cout << "\nError opening database..\n"
<< "\tQuitting System..";
exit(-1);
}
cin.clear();
cin.ignore(100, '\n');
while(fin.read(reinterpret_cast<char*>(&subjectDB), sizeof(Subject)))
{
if (!(strcmp(subCode, subjectDB.subjectCode) == 0))
{
// Print this section once
if (printOnce == 0)
{
cout << "Subject Code not found..\n";
printOnce++;
}
}
else
{
// Print this section once
if (printOnce == 0)
{
cout << "\nSubject Code: "
<< subjectDB.subjectCode
<< "\nSubject Name: "
<< subjectDB.subjectName
<< "\n"
<< endl;
cout << "Task\t"
<< "Title\t\t"
<< "Weight\t"
<< "Upon\t"
<< "Mark\t"
<< "Obtained\n";
// PrintOnce++ : 1 != 0
// So it only prints once
printOnce++;
}
cout << position + 1
<< "\t"
<< subjectDB.assessment[position].title
<< "\t"
<< subjectDB.assessment[position].weight
<< "\t"
<< subjectDB.assessment[position].upon
<< "\t"
<< subjectDB.assessment[position].taskMark
<< "\t"
<< "testing\n";
position++;
}
}
Writing a struct to a file or reading a struct from a file is totally non-portable. Compile the same code on two different compilers, or on the same compiler with different settings, and what you wrote and what you read might be very different. That's not necessarily your problem, but it will be your problem one day.
Your display code logic is flawed.
Explanation:
If the subject code is in the first record you read, you'll get the correct answer. However as soon as your fist record does not match, the "Not found" message is displayed, printOnce is incremented. If the matching subject coe is found later in the file printOnce is no longer 0 and it' will not be displayed.
Solution:
Organise your loop in the opposite way:
while (...) {
if (strcmp(..)==0) {
// your code to display the found item here
printOnce++;
break; // ?? optional: you could stop the loop at first found occurence unless you suppose there could be duplicates
}
}
and once the loop is finished, check OUTSIDE OF THE LOOP if you've found something:
if (printOnce==0) { // nothing was found in the loop
// display that nothing was found !
}
Remark:
Reading directly from file as you do has limitations. It can only work with plain old data (POD), not with more advanced types using string members or containters. For learning it's a good start but I'd suggest to foresee a Subject member function that loads the data from a stream. This proves to be more flexible when your data structure evolves: the member function could ealsily read each member data and sub-objects using the most apporpriate way.
Thanks for your help! I managed to get the function to compare properly against user input and struct file by creating a function that checks the .dat file if the subject is existing or not.
int row = checkNumberOfData(fileName);
if (row > 0)
exist = doesSubjectExist(file, fileName, code); // checks input
if (!exist)
{
file.open(fileName, ios::out | ios::app | ios::binary);
if (!file)
{
cout << "Error opening database..\n"
<< "\tQuitting System ..\n";
exit(-1);
}
strcpy(subjectDB.code, code);
cout << "Subject Name: ";
cin.getline(subjectDB.name, MAX);
cout << "No of assessment tasks: ";
cin >> subjectDB.num;
cout << endl;
.... etc
}

Program will not print line before exit() function?

I have a little project for school I am writing in C++, and we have to account for some error and just exit the program in the event that it happens. Basically, in the else statement when the expression is evaluated as false, it's like it won't write to the file the error. If I output it to the console (via cout) instead of writing it to the file it works just fine, but when I try to write it to the output file, it does not work. Basically, that is my question. My professor is requiring that all output is to the file, that's why I can't use cout. So why will it output it to the console, and not to the file?
P.S. I am outputting other stuff to the file and it's working fine, so for the record I think it is narrowed down to the little block of code in the else statement.
if(tempUnit == 'C' || tempUnit == 'F')
{
if(tempUnit == 'F')
{
temp = convertTemp(temp, tempUnit);
}
temps[a] = temp;
printTemp(outputFile, tempUnit, temp);
printTimestamp(outputFile, humanDate);
outputFile << endl;
}
else{
// this is where it doesnt work
outputFile << "Error. Incorrect temperature unit, must be " <<
"either a capital C or a capital F. Program ended.";
exit(0);
}
You need to flush the buffer before exiting the program.
outputFile << "Error. Incorrect temperature unit, must be either a capital C or a capital F. Program ended." << std::flush;
or
outputFile << "Error. Incorrect temperature unit, must be either a capital C or a capital F. Program ended." << std::endl;
Both stdout and stderr are buffered. You need to tell your program to flush your output file.
If you were doing C, you would,
fflush(stdout);
//or
fflush(stderr);
Since you are doing C++, you spell fflush, endl,
cout << std::endl; // endl does the flushing
see this stackoverflow: endl