Writing to text files

so let me ask these questions to see if I can figure out my problem.

When I open a text file in a function, it stays open for the duration of main?
I know it opened because I am using ofstream and the text file shows the current time and date.

I can write to the opened text file using the assignment operator?
ie.. osftream << texttowrite << endl;

My text is not writing to the file.
To answer several of your questions:

No, the text file does not stay open in main. It stays open for the duration of the scope of the function. If that function is main, then yes, it stays open until main shuts down.

Yes, the operator<< is used for output on the console, and for files.

If you can't figure out why your code isn't working, we can't either because we can't see it.
Last edited on
closed account (48T7M4Gy)
A file in scope also remains open until it is closed. eg input.close()

There's somebody else with exactly the same problem at http://www.cplusplus.com/forum/general/173660/
Last edited on
Oh right, to add onto what @kemort said. There's two ways of opening and closing a file (that I currently know of)

One is the aforementioned ifstream file.close(), and its complement, ifstream file.open()

The other way is ifstream fileRead( "document name");

Difference between these two? First method is explicit, meaning just like explicit constructors for self-defined classes, what is new must be deleted. Second is implicit, meaning the system or your compiler (pretty sure compiler will try to close it first before your OS takes over) will close out your file once your program runs and ends.
It is slightly incorrect.
filestream destructor will always close file if it is open. It does not matter if it was open in constructor of by call to .open.

.close likewise closes file no matter how it was open.

Usually there is little reason to call open/close manually. Let RAII do its work.
closed account (48T7M4Gy)
filestream destructor will always close file if it is open.


Is that what u really meant to write, because on its own the file will never open it seems. :)

http://stackoverflow.com/questions/748014/do-i-need-to-manually-close-an-ifstream
Last edited on
Is that what u really meant to write
Yes. I was referring to
YFGHNG wrote:
First method is explicit, meaning just like explicit constructors for self-defined classes, what is new must be deleted.
which implies that you have to call .close on files which were open by .open call and that destructor will not close such files.
Hey thanks guys for the info. I was thinking that if a file was opened in a function, I would be able to use it at any time during the main function. What I will do now is modify the placement of my file opening to correct this issue.

Also, am I correct in my thinking that with ofstream, each time I open the file and write to it, the file will be appended rather than over written?
closed account (48T7M4Gy)
Try it out. I think you'll find append is the default but you should read http://www.cplusplus.com/doc/tutorial/files/ for the options
each time I open the file and write to it, the file will be appended rather than over written?
It will be trucnated on opening: http://en.cppreference.com/w/cpp/io/basic_filebuf/open
modestring: 			"w"	
openmode & ~ate:		out, out|trunc
Action if file already exists:	Destroy contents
Action if file does not exis:	Create new 
You will need either to open it for appending (by passing ios::app to the constructor/.open) or to open it for reading and writing (ios::in | ios::out)
Last edited on
@MiinNiPaa

Oh ok I see. I just always stuck to what I was taught in that, if you explicitly do something, you must explicitly destroy it. I guess it wouldn't matter since @OP is doing simple file I/O, because I was thinking of what would happen once he wanted to introduce pointers and references into his program.
So I am attaching the code. For some reason, the file will only write to the file as I have it now. I need it to write specified text (log file text) after every action. right now, I only have pseudo functions written, What I was planning on doing was assigning a string of text to a variable in the functions and write each line to the log file after the main work of the function is completed.

I have tried every conceivable combination of calling "OpenLogFile" that I can think of. Can you guys help me get my order of operations straight so this will work the way I want it to?

Ie..
bla-bla-bla
assign text to variable
open the file
write the variable to the file...
and so on...
p.s. I tried to include the line number for the code but couldn't figure that out.
[code]
//
#include <string>
#include <iostream>
#include <fstream>
#include <cstdlib>
#include "andy.h"

//using namespace std;
//-----------------------------function declarations

//string OpenLogFile();
//void GetLogFileName(string&)
//int OpenLogFile(ofstream&);


//-----------------------------variables
//Student MyStudents;
//Student MyGrades;
ofstream OutLogName;
string LogFileName;
string TextToWrite;


//-----------------------------main body
int main()
{
cout << "Welcome to the GradeCaculator Deluxe." << endl;
GetStudentList ();
GetClassHours ();
OpenOutputFile ();
string LogFileName;
GetLogFileName(LogFileName);
OpenLogFile(OutLogName, LogFileName);

}//end main
//--------GetStudentList
string GetStudentList()

{
string FirstName;
string LastName;
int StudentId;
int NumberOfGrades;
string ClassName;
char Grade;
int Index = 0;
int LineIndex = 0;
ifstream StudentFile;
string File1;
ofstream LogFile;
student MyStudents;
grades MyGrades;
ofstream OutLogName;

cout <<"Enter the file name for the list of Students, including the extension::" << endl;
TextToWrite = "Students.txt successfully opened";

//WriteTextToLogFile(TextToWrite);
getline(cin, File1);
StudentFile.open(File1.c_str());
if(!StudentFile.is_open())
{
exit(EXIT_FAILURE);
}
// while (getline (inputFile, File1))
//{
//++LineIndex;
//}
//cout << "Number of Lines in text file is: " << LineIndex << endl;
while (StudentFile >> FirstName >> LastName >> StudentId >> NumberOfGrades)
{
MyStudents.FirstName = FirstName;
MyStudents.LastName = LastName;
MyStudents.StudentId = StudentId;
MyStudents.NumberOfGrades = NumberOfGrades;
for (int Index = 0; Index < NumberOfGrades; ++Index)
{
(StudentFile >> ClassName >> Grade);
MyGrades.ClassName = ClassName;
MyGrades.Grade = Grade;
}
}
cout << MyStudents.FirstName << ", " << MyStudents.LastName << ", " << MyStudents.StudentId << ", " << MyStudents.NumberOfGrades << endl;
cout << MyGrades.ClassName << ", " << MyGrades.Grade << endl;
// OpenLogFile(OutLogName, LogFileName);

//OutLogName << TextToWrite << endl;
return File1;
}//end GetStudentList
//--------GetClassHours
string GetClassHours()
{
//int Grades MyHours [15];
ifstream HoursFile;
string File2;
//struct grades MyGrades;
cout <<"Enter the file name for the list of Class Hours, including the extension::" << endl;
getline(cin, File2);
HoursFile.open(File2.c_str());
if(!HoursFile.is_open())
{
exit(EXIT_FAILURE);
}
cout << "\nThe file has been successfully opened for reading.\n";
return File2;
}//end GetClassHours
//-------OpenOutputFile
string OpenOutputFile()
{
ifstream OutputFile;
string File3;
cout <<"Enter the file name to write the DATA to, including the extension::" << endl;
getline(cin, File3);
OutputFile.open(File3.c_str());
if(!OutputFile.is_open())
{
exit(EXIT_FAILURE);
}
cout << "\nThe file has been successfully opened for reading.\n";

return File3;
}//end GetClassHours
//-------GetLogFileName
void GetLogFileName (string& LogFileName)
{
cout << "Enter the file name to write the Log File data to, including the extension::" << endl;
cin >> LogFileName;

}//end GetLogFileName
//-------OpenLogFile
int OpenLogFile(ofstream&, string& LogFileName)
{
ofstream OutLogName;
OutLogName.open(LogFileName.c_str());
if (!OutLogName)
{
cout << "File FAILED to open....Program Terminated" << endl;
return 1;
}

//string TextToWrite = "andy";
//cout << TextToWrite << endl;
OutLogName << TextToWrite << endl;
return 0;
}//end OpenLogFile




Hi,

One way of using code tags is to select your code, then press the <> button on the format menu.

You last post was missing the closing code tag [/code]

Good Luck!!
Any help with my code?
Once you format your post with code tags, then you will probably get more help :+)

Regards
Let's look at the following snippet:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
...
ofstream OutLogName;
...
int OpenLogFile(ofstream&, string& LogFileName)
{
    ofstream OutLogName;
    OutLogName.open(LogFileName.c_str());
    if (!OutLogName)
    {
        cout << "File FAILED to open....Program Terminated" << endl;
        return 1;
    }

...
    OutLogName << TextToWrite << endl;
    return 0;
}//end OpenLogFile


First in your function notice the missing variable name for that ofstream parameter. While this is syntacticly acceptable it is probably a mistake. The missing name means you're not using this parameter.

Second take note of the first line in that function:
ofstream OutLogName;
This creates a "new" instance of an ofstream named OutLogName, it is not related to either the parameter nor that nasty global variable named OutLogName. This instance will go out of scope when this function exits, which is probably not what you want. I recommend providing a name to the parameter in the function signature, move the declaration of OutLogName into main() and remove the nasty global variable since you you're not really using it anyway.

Lastly look at this line:
OutLogName << TextToWrite << endl;
Where have you declared and initialized TextToWrite? Why are you trying to print something is this function that should just be opening this file?

You don't seem to understand variable scope, so I suggest you review your documentation on this important feature and perhaps do a internet search on this topic using your favorite search engine.

Lastly avoid global variables whenever possible and never place a using statement inside a header file.



ok, I have read up on this stuff but it is just not clicking. In my mind, it should work anyplace that I put the "OpenLogFile" function. As long as I have a file name and a "TextToWrite" string. Please help me understand why it wont work if I move the "GetLogFileName" and the string declaration up to the top of the calls....AND then call "OpenLogFile" from "GetStudentList"?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
//
#include <string>
#include <iostream>
#include <fstream>
#include <cstdlib>
#include "andy.h"

//using namespace std;
//-----------------------------function declarations

//string OpenLogFile();
//void GetLogFileName(string&)
//int OpenLogFile(ofstream&);


//-----------------------------variables
//Student MyStudents;
//Student MyGrades;
ofstream OutLogName;
string LogFileName;
string TextToWrite;


//-----------------------------main body
int main()
{
	cout << "Welcome to the GradeCaculator Deluxe." << endl;
    GetStudentList ();
	GetClassHours ();
	OpenOutputFile ();
    string LogFileName;
    GetLogFileName(LogFileName);
    OpenLogFile(OutLogName, LogFileName, TextToWrite);
    

}//end main
//--------GetStudentList
string GetStudentList()
  
{
	string FirstName;
    string LastName;
    int StudentId;
    int NumberOfGrades;
    string ClassName;
    char Grade;
    int Index = 0; 
	int LineIndex = 0;   
  	ifstream StudentFile;
	string File1;
	ofstream LogFile;
	student MyStudents;
	grades MyGrades;
    string TextToWrite;
	cout <<"Enter the file name for the list of Students, including the extension::" << endl;
	TextToWrite = "Students.txt successfully opened";
	
	//WriteTextToLogFile(TextToWrite);
getline(cin, File1);
StudentFile.open(File1.c_str());
 if(!StudentFile.is_open())
    {
       exit(EXIT_FAILURE);
    }
    //  while (getline (inputFile, File1))
    //{
	//++LineIndex;
    //}
    //cout << "Number of Lines in text file is: " << LineIndex << endl;
    while (StudentFile >> FirstName >> LastName >> StudentId >> NumberOfGrades)
    {
    MyStudents.FirstName = FirstName;
    MyStudents.LastName = LastName;
    MyStudents.StudentId = StudentId;
    MyStudents.NumberOfGrades = NumberOfGrades;
    for (int Index = 0; Index < NumberOfGrades; ++Index)
    {
    	(StudentFile >> ClassName >> Grade);
    MyGrades.ClassName = ClassName;
    MyGrades.Grade = Grade;    
    }
    }
    cout << MyStudents.FirstName << ", " << MyStudents.LastName << ", " << MyStudents.StudentId << ", " << MyStudents.NumberOfGrades << endl;
    cout << MyGrades.ClassName << ", " << MyGrades.Grade << endl;
    //OpenLogFile(OutLogName, LogFileName, TextToWrite);
	return TextToWrite;
}//end GetStudentList
//--------GetClassHours
string GetClassHours()
{
    //int Grades MyHours [15];
	ifstream HoursFile;
	string File2;
	//struct grades MyGrades;
	cout <<"Enter the file name for the list of Class Hours, including the extension::" << endl;
	getline(cin, File2);
	HoursFile.open(File2.c_str());
  if(!HoursFile.is_open())
    {
       exit(EXIT_FAILURE);
    }
    cout << "\nThe file has been successfully opened for reading.\n";
	return File2;
}//end GetClassHours
//-------OpenOutputFile
string OpenOutputFile()
{
    ifstream OutputFile;
	string File3;
	cout <<"Enter the file name to write the DATA to, including the extension::" << endl;
	getline(cin, File3);
	OutputFile.open(File3.c_str());
  if(!OutputFile.is_open())
    {
       exit(EXIT_FAILURE);
    }
    cout << "\nThe file has been successfully opened for reading.\n";	
	
	return File3;
}//end GetClassHours
//-------GetLogFileName
void GetLogFileName (string& LogFileName)
{
	cout << "Enter the file name to write the Log File data to, including the extension::" << endl;
	cin >> LogFileName;
	
}//end GetLogFileName
//-------OpenLogFile
int OpenLogFile(ofstream& OutLogName, string& LogFileName, string TextToWrite)
{
OutLogName.open(LogFileName.c_str());
if (!OutLogName)
{
cout << "File FAILED to open....Program Terminated" << endl;
return 1;	
}
OutLogName << TextToWrite << endl;
return 0;
}//end OpenLogFile 




Just an FYI...I figured it out!!!!

woohoo!
Can anyone please tell me why that each time I write the "TextToWrite" overwrites the text in "OutLogFile" rather than appending to it?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
//
#include <string>
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <sstream>
#include "Assignment1.h"
//-----------------------------variables
string LogFileName;
string TextToWrite;
string StudentTextFile;
string ClassHoursTextFile;
string DataTextFile;
string LogTextFile;
//-----------------------------main body
int main()
{
	cout << "Welcome to the GradeCaculator Deluxe." << endl;
	cout << "Enter the name of the STUDENT file including the extension :: " << endl;
	getline (cin, StudentTextFile);
	cout << StudentTextFile << endl;
	cout << "Enter name of the CLASS HOURS file including the extension :: " << endl;
	getline (cin, ClassHoursTextFile);
	cout << "Enter name of the DATA file including the extension :: " << endl;
	getline (cin, DataTextFile);
	cout << "Enter name of the LOG file including the extension :: " << endl;
	getline (cin, LogTextFile);
    GetStudentList ();
	OpenOutputFile ();
}//end main
//--------GetStudentList
string GetStudentList()
  {
	string FirstName;
    string LastName;
    int StudentId;
    int NumberOfGrades;
    string ClassName;
    char Grade;
    int CreditHour;
    int Index = 0; 
	int LineIndex = 0;   
  	ifstream StudentFile;
	student MyStudents;
	grades MyGrades;
	string Course;
    StudentFile.open(StudentTextFile.c_str());
    if(!StudentFile.is_open())
    {
       exit(EXIT_FAILURE);
    }
   
    
    while (StudentFile >> FirstName >> LastName >> StudentId >> NumberOfGrades)
    {
    MyStudents.FirstName = FirstName;
    MyStudents.LastName = LastName;
    MyStudents.StudentId = StudentId;
    MyStudents.NumberOfGrades = NumberOfGrades;
    for (int Index = 0; Index < NumberOfGrades; ++ Index)
    {
    	(StudentFile >> ClassName >> Grade);
//===============================================
    	ifstream HoursFile;
	HoursFile.open(ClassHoursTextFile.c_str());
  if(!HoursFile.is_open())
    {
       exit(EXIT_FAILURE);
    }//end if
//===============================================
    	while (HoursFile >> Course >> CreditHour)
         if(Course == ClassName) 
		 {
		 	LookUpGradeValue(CreditHour);
		 }   	
    MyGrades.ClassName = ClassName;
    MyGrades.Grade = Grade;    
    }//end for
    }//end while
    cout << MyStudents.FirstName << ", " << MyStudents.LastName << ", " << MyStudents.StudentId << ", " << MyStudents.NumberOfGrades << endl;
    cout << MyGrades.ClassName << ", " << MyGrades.Grade << endl;
    TextToWrite = "Students.txt successfully opened. \n";
    OpenLogFile (TextToWrite);
	return TextToWrite;
}//end GetStudentList
//--------OpenClassHours
string OpenClassHours()
{
	ifstream HoursFile;
	HoursFile.open(ClassHoursTextFile.c_str());
  if(!HoursFile.is_open())
    {
       exit(EXIT_FAILURE);
    }
    TextToWrite = "Hours.txt successfully opened for reading. \n";
    OpenLogFile (TextToWrite);
	return TextToWrite;
}//end OpenClassHours
//-------OpenOutputFile
string OpenOutputFile()
{
    ifstream OutputFile;
	
	OutputFile.open(DataTextFile.c_str());
  if(!OutputFile.is_open())
    {
       exit(EXIT_FAILURE);
    }
    TextToWrite = "Data.txt has been successfully opened for reading. \n";	
	OpenLogFile (TextToWrite);
	return TextToWrite;
}//end OpenClassHours
//-------OpenLogFile
string OpenLogFile(string TextToWrite)
{
	ofstream OutLogFile;
	OutLogFile.open(LogTextFile.c_str());
	if (!OutLogFile.is_open())
	{
	 exit(EXIT_FAILURE);	
	}//end if
	 OutLogFile << TextToWrite << endl;
	 OutLogFile.close();
     return TextToWrite;	
}//end OpenLogFile
//-----LookUpGradeValue
int LookUpGradeValue (int Grade)
{
int Hours;
if (Grade == 'A')
{
	Hours = Hours * 4;
}//end ir
if (Grade == 'B')
{
	Hours = Hours * 3;
}//end ir
if (Grade == 'C')
{
	Hours = Hours * 2;
}//end ir
if (Grade == 'D')
{
	Hours = Hours * 1;
}//end ir
if (Grade == 'F')
{
	Hours = Hours * 0;
}//end ir
return Hours;
}
Topic archived. No new replies allowed.