Access of file on desktop using C++
I am using Windows 7 and I have created on the desktop a file named test.txt
. How can I access this file using C++? For example, consider following code:
#include <iostream>
#include <fstream>
#include <cstdlib>
using开发者_JAVA百科 namespace std;
int main(int argc, char *argv[])
{
fstream inout("test.txt", ios::in | ios::out | ios::binary);
if(!inout) {
cout << "Cannot open input file.\n";
return 1;
}
long e, i, j;
char c1, c2;
e = 5;
for(i=0, j=e; i<j; i++, j--) {
inout.seekg(i, ios::beg);
inout.get(c1);
inout.seekg(j, ios::beg);
inout.get(c2);
inout.seekp(i, ios::beg);
inout.put(c2);
inout.seekp(j, ios::beg);
inout.put(c1);
}
inout.close();
return 0;
}
In the fragment fstream inout("test.txt", ios::in | ios::out | ios::binary)
, what should I change to access my test.txt on desktop?
Are you asking how to access that file location from your program? If so, you need to put the file and the executable in the same directory, or include a full path to the file's location:
"%USERPROFILE%\\Desktop\\test.txt"
Unless there is a full file path starting from a drive letter (the variable %USERPROFILE% evaluates to C:\Users\ {your username} in your case) the executable will look for the file relative to its own location. Since your string contains only the file name, it will look in its own directory.
You need to provide the full path to the file. Determine what the absolute path is for the file and use that in the first argument:
fstream inout("c:\\some\\whole\\path\\to\\docmument\\test.txt", ios::in | ios::out | ios::binary);
Easiest way is to use ifstream, that is
ifstream inputfile("\path\to\input\file
);
What path it is is easiest seen using your explorer or whatever it is called these days.
I would try to provide the abosolute path to test.text
, which can be something like (I'm not sure):
C:\WINDOWS\Desktop\test.txt
The path to the desktop is available
#include <shlobj_core.h>
ofstream file;
TCHAR appData[MAX_PATH];
if (SUCCEEDED(SHGetFolderPath(NULL,
CSIDL_DESKTOPDIRECTORY | CSIDL_FLAG_CREATE,
NULL,
SHGFP_TYPE_CURRENT,
appData)))
{
int Size = 0;
string pathDesktop;
while (appData[Size] != '\0') pathDesktop+= appData[Size++];
pathDesktop+= "\\test.txt";
file.open(pathDesktop);
if (file.is_open())
{
file << "Hello World";
file.close();
}
}
精彩评论