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 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();
}
}
Related
fstream file(file_1.c_str(), ios::out | ios::in | ios::ate); //convert string to const char*
Error if File does not exist. if ( ! file ) = true
fstream file(file_1.c_str(), ios::out | ios::in | ios::app); //convert string to const char*
using ios::app seekg & seekp functions not working. file.seekg(4, ios_base::beg);
I would like to have:
USER input file name
create file if NON existing
use seekg & seekp;
Not remove the file if you run the program again.
If I understand you correctly, you need something like this:
#include <iostream>
#include <fstream>
#include <string>
int main()
{
string name;
std::cin>>name;
std::ofstream file (name.c_str());
outfile << "Text in file." << std::endl;
file.close();
return 0;
}
I have written a program which opens a file then displays line by line its contents (text file)
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main (int argc, char* argv[])
{
string STRING;
ifstream infile;
infile.open(argv[1]);
if (argc != 2)
{
cout << "ERROR.\n";
return 1;
}
if(infile.fail())
{
cout << "ERROR.\n";
return 1;
}
else
{
while(!infile.eof())
{
getline(infile,STRING);
cout<<STRING + "\n";
}
infile.close();
return 0;
}
}
What do I need to add to make the file be read only ?
(infile.open(argv[1]) is where am guessing something goes)
The class ifstream is for reading only so, problem solved. Also, did you really mean to check argc after using argv[1] ?
On the other hand, when you use fstream you need to specify how you want to open the file:
fstream f;
f.open("file", fstream::in | fstream::out); /* Read-write. */
The default mode parameter of open for ifstream class is ios::in. That is
infile.open(argv[1]);
is same as:
infile.open(argv[1], ios::in);
So you are opening the file in read-only mode.
You already open the file for read-only. Your can't write to it if you use ifstream. Even:
infile.rdbuf()->sputc('a');
is guaranteed to fail.
You don't need to do anything as the default value for the openmode is already ios_base::in. So you're already good to go :)
See here for more details: http://en.cppreference.com/w/cpp/io/basic_ifstream/open
I'm trying to open a binary file for writing without erasing the content. But I do not want to write to eof. I want to write to a specific position in file.
Here is a litte example:
ofstream out("test.txt", ios::binary | ios::app);
for(int i = 0; i < 100; i++)
out.put('_');
out.write("Hallo", 5);
out.close();
ofstream out2("test.txt", ios::binary | ios::app);
out2.seekp(10);
out2.write("Welt", 4);
out2.close();
If using app, seek doesn't work. If not using app opening file erases data. Does anybody know an answer?
try the second overload of seekp, which allows you to provide an offset and a direction, this could be begining of file in your case (i.e. ios_base::beg). This of course assumes you know what you are doing and all you want to do is overwrite an existing number of characters.
EDIT: here is fully working example:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
{
ofstream out("test.txt", ios::binary);
for(int i = 0; i < 100; i++)
out.put('_');
out.write("Hallo", 5);
}
{
fstream out2("test.txt", ios::binary | ios::out | ios::in);
out2.seekp(10, ios::beg);
out2.write("Welt", 4);
}
}
When opening with ios::app, it is as if you open a new file that just happened to be attached to an existing file: you can not access the existing file. I'm not sure, because I would do as in Kerrek's answer, but if you really want to try, you probably have to open with "ios::in | ios::out", similar to fopen("test.txt", "rw").
Or as crashmstr points out: ios::out might be enough.
You cannot magically extend the file from the middle. Perhaps easiest to write to a new file: First copy the initial segment, then write your new data, then copy the remaining segment. When all is done, you can overwrite the original file.
According to the specification of fstream here
fstream::open
the ios::app "Sets the stream's position indicator to the end of the stream before EACH output operation." So ios::app doesn't work for replacing, seeks of any sort fail, at least for me.
Just using ios::out does wipe out the file contents preserving only the size, basically turning the file into trash.
ios::in|ios::out turned out as the only working thing for me.
Working Code: This code searches for a string (OLD-STRING) in cout.exe and replaces with a new string (NEW-STRING).
`#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char *argv[])
{
fstream ifs;
ifs.open ("C:\\Users\\user\\Desktop\\cout.exe", fstream::binary | fstream::in | fstream::out);
std::string str((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>());
size_t pos = str.find("OLD-STRING");
if (pos != string::npos)
{
cout << "string found at position: " << int(pos) << endl;
ifs.seekp(pos);
ifs.write("NEW-STRING", 10);
}
else
{
cout << "could not find string" << endl;
}
if (ifs.is_open())
ifs.close();
return 0;
}`
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
int main(int argc,char *argv){
fstream inout("C:\\Users\\7\\Desktop\\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.seekg(j,ios::beg);
inout.put(c1);
}
inout.close();
return 0;
}
why this code writes can't open file
EDIT:
i have made corrections but here is one problem
in test.txt is written such thing
maiko
miyvarxar
shen
me
so it should write
me shen miyvarxar maiko
but it does not write anything
please help
This seems to work for me:
using namespace std;
int main()
{
fstream inout("C:\\Users\\turdfurguson\\Turds\testfile.txt", ios::in | ios::out | ios::binary);
if (inout.good())
cout << "OK!" << endl;
}
Provided you have a "C:\Users\turdfurgson\Turds\testfile.txt" file that is readable and writable.
The code you've provided looks fine.
You may have supplied the wrong path or something like that.
You could also try attempting to open that file in read only mode
and see if that is ok:
std::ifstream in("path", std::ios::binary);
if (!in) {
// fail
}
I've been all over the ifstream questions here on SO and I'm still having trouble reading a simple text file. I'm working with Visual Studio 2008.
Here's my code:
// CPPFileIO.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <fstream>
#include <conio.h>
#include <iostream>
#include <string>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
ifstream infile;
infile.open("input.txt", ifstream::in);
if (infile.is_open())
{
while (infile.good())
cout << (char) infile.get();
}
else
{
cout << "Unable to open file.";
}
infile.close();
_getch();
return 0;
}
I have confirmed that the input.txt file is in the correct "working directory" by checking the value of argv[0]. The Open method just won't work.
I'm also having trouble debugging- should I not be able to set a watch on infile.good() or infile.is_open()? I keep getting
Error: member function not present.
EDIT: Updated code listing with full code from .CPP file.
UPDATE: The file was NOT in the Current Working Directory. This is the directory where the project file is located. Moved it there and it works when debugging in VS.NET.
Try using the bitwise OR operator when specifying the open mode.
infile.open ("input.txt", ios::ate | ios::in);
The openmode parameter is a bitmask. ios::ate is used to open the file for appending, and ios::in is used to open the file for reading input.
If you just want to read the file, you can probably just use:
infile.open ("input.txt", ios::in);
The default open mode for an ifstream is ios::in, so you can get rid of that altogether now. The following code is working for me using g++.
#include <iostream>
#include <fstream>
#include <cstdio>
using namespace std;
int main(int argc, char** argv) {
ifstream infile;
infile.open ("input.txt");
if (infile)
{
while (infile.good())
cout << (char) infile.get();
}
else
{
cout << "Unable to open file.";
}
infile.close();
getchar();
return 0;
}
Sometimes Visual Studio puts your exe file away from your source code. By default VS may only look for the file starting from your exe file. This process is a simple step for getting the input txt file from the same directory as your source code. Should you not want to fix your IDE setup.
using namespace std;
ifstream infile;
string path = __FILE__; //gets source code path, include file name
path = path.substr(0,1+path.find_last_of('\\')); //removes file name
path+= "input.txt"; //adds input file to path
infile.open(path);
Hopefully this helps other people for a quick solution. It took me a while to find this setup myself.
I've found two problems in your code:
a) syntax error in "ios::ate || ios::in" => should be "ios::ate | ios::in"
b) "ios::ate" sets the cursor to the end of file - so you get nothing when you start reading
So just remove "ios::ate" and you are fine :)
ciao,
Chris
infile.open ("input.txt", ios::ate || ios::in);
|| is the logical or operator, not the bitwise operator (as Bill The Lizzard said).
so i guess you are doing the equivalent to:
infile.open ("input.txt", true);
(assuming neither ios::ate or ios::in are 0)
Try using:
ifstream fStm("input.txt", ios::ate | ios::in);
I'm also having trouble debugging- should I not be able to set a watch on "infile.good()" or "infile.is_open()"? I keep getting "Error: member function not present."
and the proper includes:
#include <fstream>
etc.
If you use the default Vs code setup, place the text file that you want to read from in the same folder as your executable, I know it is not pretty but yeah it works