Andrew Ryan
Andrew Ryan

Reputation: 37

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

Upvotes: 1

Views: 787

Answers (4)

Jon Purdy
Jon Purdy

Reputation: 54981

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

Upvotes: 3

philippe lhardy
philippe lhardy

Reputation: 3286

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++...

Upvotes: 4

michaelwayman
michaelwayman

Reputation: 196

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

Upvotes: 2

Steve
Steve

Reputation: 11963

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

Upvotes: 1

Related Questions