C++ doesn't create text file - c++

I'm new to the StackOverFlow.
I'm using Dev-C++ and I wanted to write a text file with my C++ program. But the problem is my program doesn't create a text file.
Instead it creates a file named "026.Writing-to-Files-With-Ofstream.o". (My cpp file's name is: 026.Writing-to-Files-With-Ofstream.cpp)
That's not what I wanted.
Also Dev-C++ doesn't give me any errors or warnings.
I tried using CodeBlocks and still the same result. It creates a ".o" file and not a text file.
Here is my code:
#include <iostream>
#include <fstream>
int main(){
std::ofstream file ("hello.txt");
file << "Hello There!"; //line 5
file.open("hello.txt"); //line 6
return 0;
}
I tried everything. Nothing in the desktop or in my working directory. I switched the lines (5 and 6). I really need your help.

You do too much.
std::ofstream file ("hello.txt");
This line creates ofstream and opens it for writing. When the stream is opened for writing, it's contents on disk is emptied!
file << "Hello There!";
This like prints something to the ofstream. Usually, it is stored in the buffer not yet saved to disk or displayed on screen. (To actually save something to disk, you need endl, flush, or to close the file. The file is closed when the block where it was opened ends, or when you close it explicitly.)
file.open("hello.txt"); //line 6
You again open the file for output, thus emptying it's contents on disk, and emptying the buffer.
}
whatever is in the buffer, saved to disk. But there is nothing in the buffer, because you opened the file again!
You should remove the line 6.

I see 2 problems here:
First, you just compiled the code so the output is a compiled object file called "026.Writing-to-Files-With-Ofstream.o". You need to run it.
Second, the code is not entirely correct. You already opened the file when you did std::ofstream file("hello.txt"); so you do not need line 6. You need to open the file before writing to it. Also You need to close the file after you finished writting: file.close();

I solved it! I searched all the Windows files/folders with the search option on the start menu. It took a long time (10 mins) but i finally found out where the file was. It was in the inside of a folder named "VTRoot". Thanks for the help tho

Related

Keeping previous record, how to add new text in textfile using fstream in c++

In C++ I have made a program which writes given data into a text file (notepad). The problem is when I restart my program and enter other data then it clears the previous one and adds new data.
I want to keep my previous data safe, and add new data in a new line in text file.
For example,
I wrote "I am a programmer" in my program.
Now my text file will show this:I am a programmer
Now if I restart my program and write "I am unemployed". Then textfile shows this: I am unemployed.
But I want my file to be:
I am a programmer
I am unemployed
Please, Help...
You need to open the file with the append flag. If you're using fstream, it looks something like this:
#include<fstream>
using namespace std;
fstream outfile = fstream("myfilename.txt", ios_base::app)
See reference http://www.cplusplus.com/reference/fstream/fstream/open/

Open a txt file with texteditor while its already opend by "fopen()" and in use?

Logger for my program. I saw in another program that it’s somehow possible to open and read a file with text editor while the program is still using it. Seems it just opens a copy for me and continue logging in the background. This kind of log system I need too. But if I use fopen() I only can open and read the file with my text editor if the Programm already closed it with fclose(); This way would work but I think its a very bad solution and also very slow... to open and close the file on every log :S
Someone knows how the needed log system is working?
P.S. I'm working in VisualStudio 2013 on Windows 8.1
Sry for my bad English :S
There are 2 different problems.
First is writing of logs. In a Windows system, the buffering will cause the data to be actually written to disk :
if you close the file
when you have a fair quantity of new data (unsure between several ko and several Mo)
if you explicitely flush
Unless if you have a high throughput, I would advise to at least flush (if not close) after each write to avoid loosing logs if program crashes. And it also allows you to read the log file in real time.
Second is reading. Vim for example is known to be able to monitor a file that can be modified by an external process. It will open a popup saying that file has been modified and offer to reload it. I do not know what notepad does in same conditions. But :
it does not have sense unless first problem has gone
it is not very efficient since you will reload whole file each time
IMHO, you'd better write a custom reader that mimics Linux tail -f :
read (and display) until end of file
repeteadly read (with a short sleep after an unsuccessful read) to process newly added data
It all depends on the text editor you are using. Some will notice edit to the file and ask you if you want to reload a fresh version.
If you work on linux, and you'd like to have an idea of what's happening in real time you could do someting like
tail -f <path-to-file>
or if the file doesnt yet exist
watch -n 0,2 "cat <path-to-file> | tail"
which will display the content of the file and refresh it every 0.2 sec
Thx for your fast answers :)
Crazy.. i was working so long with fopen() and found no solution.. also the fflush(pFile) didnt help (I wasnt able to open file.. always error that its already in use by another program). I never tryed the fstream. Seems fstream solved my problem now. I can open my file with msnotepad.exe while the program is still writing to the file :) Here a small test-code:
#include <fstream> #include <iostream> using namespace std;
int main(){
ofstream FILE;
FILE.open("E:\\Log.txt");
for (size_t i = 0; i < 50; i++)
{
FILE << "Hello " << i << endl;
cout << "log" << endl;
_sleep(500);
}
FILE.close();
cout << "finish" << endl;
return 0;}

C++ Open file seems to ruin file after run

Simply put, I double click on image1 in its file and it opens. I run the code bellow to open image1 and nothing comes up. So I go into the file with image1 again, double click on it, and windows photo viewer said, "Windows Photo Viewer can't display this picture because the file is empty." I did this with two other test images and the same thing is happening. Nothing important has been lost but this method seems to be erasing whichever file it tries to open and I'm very curious as to why and how I can fix it.
#include <iostream>
#include <fstream>
#include <chrono>
#include <thread>
void main()
{
std::ofstream imagetest;
imagetest.open("C:\\Users\\Filepath\\image1.jpg");
std::chrono::milliseconds dura(2000);
std::this_thread::sleep_for(dura);//Kept the sleep in because I didn't know if having the console up would affect the file/image from opening.
}
C++ is at lower level than scripts. open does not mean START.
You will have to execute a batch script with START C:\Users\Filepath\image1.jpg.
Or to learn many more libraries to do that in C++...
ofstream stands for “output file stream”. In addition to creating files that doesn’t exist, it also erases the contents of files that do exist. So you are opening an existing file for writing, and blowing away its contents in the process. You probably want ifstream, “input file stream”, for reading.
If you want to “open” the file in the sense of launching the default Windows application to read the file, you can use the Windows start command via system:
system("start \"C:\\Users\\Filepath\\image1.jpg\"");
Or the Windows ShellExecute API:
#include <windows.h>
ShellExecute(
NULL,
"open",
"C:\\Users\\Filepath\\image1.jpg",
NULL,
NULL,
SW_SHOWNORMAL
);
First,
std::ofstream imagetest;
is using the kernel to open the file for reading the file data..
this is probably what is corrupting the file from "opening" when you double click on it in windows
if you want to have windows open the image for viewing using the default application then you need a different method call because ofstream.open is not what you want.
try:
http://msdn.microsoft.com/en-us/library/windows/desktop/bb762153(v=vs.85).aspx
ShellExecute(NULL,"open","C:\\Users\\Filepath\\image1.jpg",NULL,NULL,SW_SHOW);
If you open a file stream for WRITE, then it will wipe all the content of that file, just like when you do that on a txt file. So you would always want to open the stream for read mode if you don't want that to happen

File opening modes in C++

Can I open a .xls or .PDF file using the open() function in C++ with binary mode and read its contents? If not, how can I build an application program that can read the contents of files with such file formats (and maybe more)
Yes, you can open any file in your filesystem as a binary file, and you can read it too (as long as your operating system allows the file to be opened based on file access rights, and no other application has got a lock on it, etc).
Next you'll probably ask "How do I interpret a PDF or XLS file?" and that's a whole other kettle of fish as they say here in England. Neither PDF, nor XLS files are straight forward to "understand". A PDF librar that I looked at recently contains several dozen files, and is several megabytes of source code. I've worked with XLS files in Python, and the code there was a few thousand lines of code.
Simple reading would be:
#include <iostream>
#include <fstream>
#include <algorithm>
#include <iterator>
std::vector<char> readfile(std::string const& fname)
{
std::ifstream ifs(fname.c_str(), std::ios::binary);
std::istreambuf_iterator<char> f(ifs.rdbuf()), l;
std::vector<char> bytes;
std::copy(f, l, std::back_inserter(bytes));
return bytes;
}
int main()
{
auto bytes = readfile("my.pdf");
}
The argument mode points to a string beginning with one of the following
sequences (Additional characters may follow these sequences.):
``r'' Open text file for reading. The stream is positioned at the
beginning of the file.
``r+'' Open for reading and writing. The stream is positioned at the
beginning of the file.
``w'' Truncate file to zero length or create text file for writing.
The stream is positioned at the beginning of the file.
``w+'' Open for reading and writing. The file is created if it does not
exist, otherwise it is truncated. The stream is positioned at
the beginning of the file.
``a'' Open for writing. The file is created if it does not exist. The
stream is positioned at the end of the file. Subsequent writes
to the file will always end up at the then current end of file,
irrespective of any intervening fseek(3) or similar.
``a+'' Open for reading and writing. The file is created if it does not
exist. The stream is positioned at the end of the file. Subse-
quent writes to the file will always end up at the then current
end of file, irrespective of any intervening fseek(3) or similar.

Why does the delete event occur on file write?

I am using Kernel Queues in OS X to watch for file events (sample code) and when I run the sample code on a file foo.bar and then modify the file, the sample prints out that it recieved a delete event for the file. How could this be? Is this a bug?
By "modifying" the file, I take it you mean editing it or whatever.
No, this is not a bug. Most text editors write the contents of a modified file in another file, then flush and close it, then delete the original and rename the other file to the original.
On the other hand, some "simple" edit operations, such as appending a line to a file using echo whatever >>thefile, will not delete the file but open/seek/write/flush/close it.