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
Related
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
I am creating an application to manage other applications or exe files on a user's computer, and stop them from accessing them at certain times (like ColdTurkey's application blocking feature).
The way I am trying to do this has not been working so far - I attempted to do this by opening the file dwShareMode set to 0 using the CreateFile function. This seems to work for files such as text files and does not allow the file to be opened, however this is not the case if I try and do this same approach on exe files, and the user is free to open the file.
I assume that exe files are not 'read' in the same way by Windows as a text file is read by notepad and that that means setting the dwShareMode to 0 does not affect it being opened, however I do not know what the difference between these are. Any help would be appreciated.
Code here (for the text file):
#include <windows.h>
#include <string>
#include <iostream>
using namespace std;
int main()
{
HANDLE test;
test = CreateFile("test.txt",
GENERIC_WRITE,
0,
NULL,
CREATE_NEW,
FILE_ATTRIBUTE_NORMAL,
NULL);
cout << "press enter to stop blocking application: ";
string b;
getline(cin, b);
cout << endl;
CloseHandle(test);
return 0;
}
Your code works fine for me to block execution of the file. You do need to specify OPEN_EXISTING instead of CREATE_NEW (because you're not trying to create a new file here).
Not a windows expert -- I'm used to Unix/Linux and use the Cygwin package so I can program "in Unix" on my Windows desktop -- but it looks to me like you need to set the lpSecurityAttributes parameter, the one that comes after dwShareMode.
I think the following page might be helpful:
https://msdn.microsoft.com/en-us/library/windows/desktop/aa364399(v=vs.85).aspx
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;}
I have written a code in which i want to open a HTM file when i select a particular option...
To achieve this i have created a batch file and opened it using system() as shown in code..
This is my code:
code:
#include <iostream.h>
#include <stdlib.h>
#include <dos.h>
#include <process.h>
void main()
{
cout<<"Hello World";
delay(3000);
system("a.bat");
delay(1000);
}
a.bat code:
start iexplore.exe c:\Turbo\TC\BIN\Hello.htm
When i just use this line in command line it executes but when i want to execute it using c++ code i get a bad filename or command error...
Please tell me if i am going wrong somewhere here.. or what can i do.
Please help..
Thank You..:)
Since most of your code isn't particularly portable anyway, the right way is almost certainly to use ShellExecute to "execute" the HTML file directly. I, for one, would have to be pretty desperate before I'd put up with a program using IE to open HTML files.
ShellExecute is Windows-specific, but your code isn't particularly portable right now. I suppose Unix (or similar) systems wouldn't actually stop you from naming a shell script whatever.bat, but it's certainly uncommon. You certainly shouldn't expect iexplore.exe to be available on most though (nor for executables in general to have a '.exe' extension).
ShellExecute(NULL, NULL, "c:\\Turbo\\TC\\BIN\\Hello.htm", NULL, NULL, SW_SHOWNORMAL);
You can use CreateProcess() API (http://msdn.microsoft.com/en-us/library/windows/desktop/ms682425.aspx)
PROBLEM HISTORY:
Now I use Windows Media Player SDK 9 to play AVI files in my desktop application. It works well on Windows XP but when I try to run it on Windows 7 I caught an error - I can not remove AVI file immediately after playback. The problem is that there are opened file handles exist. On Windows XP I have 2 opened file handles during the playing file and they are closed after closing of playback window but on Windows 7 I have already 4 opened handles during the playing file and 2 of them remain after the closing of playback window. They are become free only after closing the application.
QUESTION:
How can I solve this problem? How to remove the file which has opened handles? May be exists something like "force deletion"?
The problem is that you're not the only one getting handles to your file. Other processes and services are also able to open the file. So deleting it isn't possible until they release their handles. You can rename the file while those handles are open. You can copy the file while those handles are open. Not sure if you can move the file to another container, however?
Other processes & services esp. including antivirus, indexing, etc.
Here's a function I wrote to accomplish "Immediate Delete" under Windows:
bool DeleteFileNow(const wchar_t * filename)
{
// don't do anything if the file doesn't exist!
if (!PathFileExistsW(filename))
return false;
// determine the path in which to store the temp filename
wchar_t path[MAX_PATH];
wcscpy_s(path, filename);
PathRemoveFileSpecW(path);
// generate a guaranteed to be unique temporary filename to house the pending delete
wchar_t tempname[MAX_PATH];
if (!GetTempFileNameW(path, L".xX", 0, tempname))
return false;
// move the real file to the dummy filename
if (!MoveFileExW(filename, tempname, MOVEFILE_REPLACE_EXISTING))
{
// clean up the temp file
DeleteFileW(tempname);
return false;
}
// queue the deletion (the OS will delete it when all handles (ours or other processes) close)
return DeleteFileW(tempname) != FALSE;
}
Technically you can delete a locked file by using MoveFileEx and passing in MOVEFILE_DELAY_UNTIL_REBOOT. When the lpNewFileName parameter is NULL, the Move turns into a delete and can delete a locked file. However, this is intended for installers and, among other issues, requires administrator privileges.
Have you checked which application is still using the avi file?
you can do this by using handle.exe. You can try deleting/moving the file after closing the process(es) that is/are using that file.
The alternative solution would be to use unlocker appliation (its free).
One of the above two method should fix your problem.
Have you already tried to ask WMP to release the handles instead? (IWMPCore::close seems to do that)