how i could solve this problem with ifstream - c++

when I run this code its only work with visual studio, in online compiler always tell me "cant opening file"
#include <iostream>
#include<fstream>
#include<string>
#include<iomanip>
using namespace std;
ifstream input("C:/Users/ACER/Desktop/words.txt");
if (!input.is_open())
{
cout << "cant opening file";
return 0;
}

An online compiler probably cannot open file on your computer using C++ code since that's not how the web works. It would have to route through some Javascript system, which is possible to create, however it seems the creators did not implement that when setting up their compiler.
You might try using file://C:/Users/ACER/Desktop/words.txt and double checking your path. Web browsers use that file:// thing when accessing local file i.e. if you had a web page on your computer it could be like file://C:/Users/ACER/Documents/index.html or something.
If that doesn't work, it just doesn't have the capability to load or save local files like that.

When you were attempting to use the code on an online compiler, most of the time you are actually compiling the code on their server, instead of on your computer.
What that means is that when you are trying to open "C:/Users/ACER/Desktop/words.txt", you are actually attempting to open a text file that is located on their server. And in most cases, you wouldn't be permitted to lookup any directory other than the one you are in. Even if you were permitted to do that for some reason, the chances they also have that text file on their server in the same location is gonna be really low.
Some comments above mentioned that many online compilers often don't have the facility to manipulate files. One that I often use do have the ability to do so in case you were looking for one: https://replit.com/#Ranoiaetep/IndianredSquigglyPrinters
.Note that the working directory is defaulted as your root directory.

Related

How to check if any files are open in a directory?

I am trying to delete all files in a folder, but if a file is left open, it will not delete. I need to check the folder for any open files, write their names to a text document, and then close the open files. As I don't have much experience, I am first trying to check one file in the same folder, then all in the same folder, then all in a different folder. I don't want to be to needy or demanding, so just some help with the first step would be nice.
I don't have a ton of experience coding, but I have tried using fstream and (name.is_open). I may be using them wrong, so I have not yet ruled them out.
// ifstream::is_open
#include <iostream> // std::cout
#include <fstream> // std::ifstream
void checkFiles() {
int done = 0;
while(done != 1){
std::cout << "Enter 0 for continue or 1 for done: ";
std::cin >> done;
std::ifstream ifs ("test.txt");
if (ifs.is_open()) {
// Print that file is open, then close
std::cout << "File is open\n";
std::ifstream.close():
}
else {
std::cout << "File not open\n";
}
}
For this bit of code, if the file is open, it should say "File is open."
If not, it should say "File not open"
Even if I force quit the .txt file, it still says that it is open.
Eventually, I want to have a new file that displays what files were open, as well as closing all the open files.
Standard C++ offers us the filesystem library to handle files and directories (standardized in C++17). However, checking which files are open is not - as far as I can tell - a feature of that library.
The is_open() method for std::fstream's is something completely different than what you're trying to check for: It tells you whether the particular stream object is in an open state (which would mean association with an open file) - and it doesn't use the OS to check which files are open. Typically, it's just a way to check whether you've closed it someplace else in your own program; at most, it might ensure that the OS has not unilaterally closed the OS-side file access handle. So, you won't get anywhere in that direction.
I also believe, though I'm not 100% certain, that Boost doesn't have a library which offers this capability, either. Boost's filesystem library is almost identical to std::filesystem, as the latter was based on it.
So, to the best of my knowledge, you either need to directly use operating-system-specific calls to do this, or look for a library offering this functionality, elsewhere.
If you haven't found anything else, you could track how this is currently done with what's available in userspace. There's a utility called lsof. It's available on some operating systems based on Linux, Darwin, FreeBSD and Solaris (e.g. available on MacOS). It's maintained here. The source code seems to be rather atrocious C. An intrepid developer could parse that mess, figure out what it does, extract the parts relevant for your specific use case, and refactor it into a reasonable, readable and short(ish) C++ function. I realize you (OP) might not be up for it at this point, but - maybe someone else reading this answer will get inspired to do it.
The pfiles command shows the open files for a process. You can run it for all or some processes.
However, Solaris (and UNIX) in general allows you to delete open files. The file can still be read and written while it is open (but deleted), but nobody else can open the same file and the file will be deleted when all processes have the file closed.

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++ ofstream System.AccessViolation

I have a problem. I'm writing to a log file, but when I do the application throws:
An unhandled exception of type 'System.AccessViolationException' occurred in ****
Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
The code (unmanaged) I'm using is this one:
inline bool writeLog(string message)
{
ofstream myfile;
myfile.open(mStrSource.c_str(), ios::in | ios::out | ios::app);
if(!myfile.is_open())
{
throw "Unable to open the file: " + mStrSource;
}
myfile << "TESTE" << endl;
myfile.close();
return true;
};
When receiving this error, the code points to the _Lock() of file fstream:
virtual void __CLR_OR_THIS_CALL _Lock()
{ // lock file instead of stream buffer
if (_Myfile)
_CSTD _lock_file(_Myfile);
}
Other info:
Developed under VS2010 (Incially the project was Winx32 but now it's Winx64) (.NET Framework 4).
The open() method of ofstream creates the file and the file is writable but throws the exception when try's to write on the file.
Thank you guys in advanced.
Check to make sure your application has rights to write to a file in that location. A standard user in Windows cannot access the whole file system (especially for writing). Either require the app to have admin rights (not recommended for "normal" apps) or write to a place that standard users can get to (e.g. My Documents directory).
Also, make sure the file is not opened for exclusive use by another app like Excel or Word. They have a habit of locking files when opening them.
Another thing to look at is during development, sometimes the .NET runtime/VS debugger will leave a file locked that you were working with after a crash. Try closing/reopening Visual Studio to help with that.
Ok guys,
For future notice, the problem was related to the configuration of the project. When I converted the project from vs2008 to vs2010, from .net 3.5 to .net 4 and from x32 to x64 something didn't quite go right.
So I reverted everything back and converted again in a more controlled environment and now i can open/write/close files without a problem.
Thanks anyway guys.

Xcode c++ cant access file through code

I have added an image "padimage.png" to my resources folder and set add to target and make copy if needed checked. Then in my c++ code I have the following code to check if it can reach the file
std::ifstream my_file("padimage.png");
if (my_file.good())
{
std::cout << "could read file \n";
} else {
std::cout << "could not read file \n";
}
This fails meaning I can't reach the file. I have checked in the debug build folder and the image is there under the resources folder, I have also tried alternative paths to the file like "resources/padimage.png" || Resources/padimage.png || ../Resources/padimage.png etc. etc.
I am fairly new to c++ still so I don't quite understand how it is suppose to find files or what path it searches relative to. Also I am sure this is quite an easy problem but I somehow can't solve it.
All help is much appreciated.
Just for your own sanity, do the following before anything else.
char wd[1024];
std::cout << getcwd(wd, sizeof(wd)) << std::endl;
You may be surprised at where you are, and thus why you can't open your file. When running from the IDE you can specify the location of your working directory under the Product/Edit Schemes... area of Xcode (among other places).
Thanks to a suggestion from WhozCraig I have managed to get it working by using the root of the project and then creating a standalone file next to the application like so:
./padimage.png
however this is not ideal. This means I would have resources outside of the project.
But after some trial and error I managed to navigate into the programs package contents by using .app to the package name;
./ProjectName.app/Contents/Resources/padimage.png

How to create a text file in a folder on the desktop

I have a problem in my project. There is a project folder on my desktop. I want to create a text file and write something include this text file. That is my code:
ofstream example("/Users/sample/Desktop/save.txt");
But I want to it could been run the other mac. I don't know what I should write addres for save.txt.
Can anyone help me?
Create a file and write some text to it is simple, here is a sample code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
std::ofstream o("/Users/sample/Desktop/save.txt");
o << "Hello, World\n" << std::endl;
return 0;
}
I hope that answers your question but I am not sure if i understand your question correctly, If not please add the details correctly of what you are trying to acheive.
[Update]:
Okay I guess the comment clears the problem.
Your real question is, You want to save the file in the desktop of the user who is playing the game. So getting the path of the current user's desktop is the problem.
I am not sure if there is an portable way to get desktop path but it can be done in following ways:
In Windows:
Using the SHGetSpecialFolderPath() function.
Sample code:
char saveLocation[MAX_PATH] = {0};
SHGetSpecialFolderPath(NULL, saveLocation, CSIDL_DESKTOPDIRECTORY, FALSE);
//Now saveLocation contains the path to the desktop
//Append your file name to it
strcat(saveLocation,"\\save.txt");
ofstream o(saveLocation);
In Linux:
By using environment variables $HOME
sample code:
string path(getenv("HOME"));
path += "/Desktop/save.txt";
ofstream o(path);
Rules defining where-you-should-save-file vary from platform to platform. One option would be to have it part of your compile script (that is you #define SAVEGAME_PATH as part of your compilation configuration), and thus your code itself remain more platform-agnostic.
The alternative is to find a save-data-management library that is already designed to be ported across different platforms. Whether it'd be a C or C++ or whatever-binary-interoperable library then no longer matters.
Just don't expect that to be part of C++ (the language).
if you want your program to run across platform,you'd better use the
relative path.
eg. "./output.txt",or better “GetSystemDirectory()”to obtain the system
directory to create a file,and then you could write or read the file
with the same path..