In C++ I need to check whether a entered file name exists in that folder or not. I'm writing code for Linux, using the g++ compiler.
please help guys :)
I saw this code somewhere on net for my problem but I strongly feel it wont serve my purpose:
ofstream fout(filename);
if(fout)
{
cout<<"File name already exists";
return 1;
}
You can do this by testing with an ifstream, but there is a subtle difference between using that and the C level stat() interface.
#include <cerrno>
#include <cstring>
#include <iostream>
#include <fstream>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
using namespace std;
int main (int argc, const char *argv[]) {
if (argc < 2) {
cerr << "Filepath required.\n";
return 1;
}
ifstream fs(argv[1]);
if (fs.is_open()) {
fs.close();
cout << "ifstream says file exists.\n";
} else cout << "ifstream says file does not exist.\n";
struct stat info;
if ((stat(argv[1], &info)) == -1) {
if (errno == ENOENT) cout << "stat() says file does not exist.\n";
else cout << "stat() says " << strerror(errno) << endl;
} else cout << "stat() says file exists.\n";
return 0;
}
If you run this on a file that exists and you have read permission on, you'll get the same answer both ways.
If you run this on a file that does not exist, you get the same answer both ways.
If you run this on a file that exists but you do not have read permissions on, you'll get two different answers. fstream will say the file does not exist, but stat() will say it does. Note that if you run ls in the same directory, it will show the file, even though you cannot read it; it does exist.
So if the last case is not significant -- i.e., a file you can't read might as well not exist -- then use the ifstream test. However, if it is important, then use the stat() test. See man 2 stat (the 2 is important) for more, and remember, to use it you need:
#include <cerrno>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
cerrno is required to check errno if stat() fails, which can happen. For example, if read permission on a directory in the path is denied, then stat() will fail and errno will be equal to EACCES; if you try it with the above program you'll get stat() says Permission denied. This does not mean the file exists. It means you can't check whether it exists or not.
Beware, if you have not used errno before: You must check immediately on a failed call, before you make any others which may set it differently. It is, however, thread safe.
If you want to be cross-platform and C++'y I recommend the Boost Filesystem library.
For your purposes I think something similar to this Boost sample code
#include <iostream>
#include <boost/filesystem.hpp>
using namespace boost::filesystem;
int main(int argc, char* argv[])
{
path p (argv[1]); // p reads clearer than argv[1] in the following code
if (exists(p)) // does p actually exist?
{
if (is_regular_file(p)) // is p a regular file?
cout << p << " size is " << file_size(p) << '\n';
else if (is_directory(p)) // is p a directory?
cout << p << "is a directory\n";
else
cout << p << "exists, but is neither a regular file nor a directory\n";
}
else
cout << p << "does not exist\n";
return 0;
}
would do the job.
Maybe what you want is fstat:
http://codewiki.wikidot.com/c:system-calls:fstat
Related
I am trying to open a text file, and the code below is my attempt:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
std::ifstream file;
file.open("InputFile.txt");
std::string fileOutput;
if (file.is_open())
{
while (!file.eof())
{
file >> fileOutput;
std::cout << fileOutput << std::endl;
}
}
else
{
std::cout << "File failed to open" << std::endl;
}
file.close();
return 0;
}
The text file is located on my desktop, and it only contain two integers.
Whenever I run the code above, it will show me the "file failed to open" message. I am completely new to c++, so I really don’t have any idea why my code is not working. So any comments would be appreciated.
The text file is located on my desktop
So where is your C++ source file, is it located in my desktop as well?
Note this code file.open("InputFile.txt"); tries to open the InputFile.txt in the current folder, that means it only works if both C++ source file and your text file are in the same folder. That seems to be your problem.
Like #ShadowRanger's this comment, the existing answers are both inaccurate. The argument for file.open() needs to either 1. reflect the relative location of the text file in relation to the current working directory (where you are calling the executable from), or 2. give the absolute location of the text file on the disc.
I suggest the following solution:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char** argv) {
if (argc != 2) {
std::cout << "incorrect number of inputs" << "\n";
std::cout << "correct usage: this_executable.exe file_location" << "\n";
return -1;
}
std::ifstream file;
file.open(argv[1]);
std::string fileOutput;
if (file.is_open())
{
while (file >> fileOutput)
{
std::cout << fileOutput << std::endl;
}
}
else
{
std::cout << "File "<< argv[1] <<" failed to open" << std::endl;
}
file.close();
return 0;
}
This solution takes the file's address info out of the code. With this solution, when you call your executable, the file's address(directory path + file name) is given to the executable at run-time rather than compile-time. Now, you'd run the executable like:
C:\path_to_your_exe>my_executable.exe C:\path_of_your_txt_file\InputFile.txt
The benefits of this approach are:
You can change the file's name / path without having to recompile the code;
On the commandline, it is easier to check that the target file's address is correct by tab completion
Also note:
As #ShadowRanger also pointed out the Why is “while ( !feof (file) )” always wrong? issue which I was not aware of.
If you are wondering what argv[1] means, see this guide for more information on commandline arguments for C++. You also want to make sure to catch situations when the user did not specify an input (meaning argv[1] is invalid, thus the argc != 2)
Unless the file you are opening and your executable are in the same directory, the same message will be printed since it will search for the file in the current working directory. You can specify the absolute path to the file on your desktop using %USERPROFILE%\\Desktop\\InputFile.txt or any other environmental variable that maps the absolute path of a disk, from which your file can be found.
Hey everyone. I need to write a POSIX program to search through an entire file system for a specified file starting at the top directory. I've got some code which isn't done at all, but when I run it, and check to see if a particular file is a directory, it's saying this file which is not at all a directory is a directory and is trying to move into it, causing an error. I'm not sure how I can tell it that this type of file isn't a directory.
Here's my code. I know it's not perfect and I could probably do some things differently in the way of getting the directory names and passing them into the function. Either way, I'm pretty sure I have to do this recursively.
The file in question is /dev/dri/card0 and I'm running this from a Debian virtual machine.
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <unistd.h>
#include <time.h>
#include <stdint.h>
#include <locale.h>
#include <langinfo.h>
#include <fcntl.h>
#include <iostream>
#include <stdio.h>
#include <string>
using namespace std;
void SearchDirectory(string file_Name, string directory){
string new_Directory = directory;
DIR *dirp;
dirp = opendir(directory.c_str());
struct dirent *dptr;
struct stat statStruct;
while(dptr = readdir(dirp)){
stat(dptr->d_name, &statStruct);
if( S_ISDIR(statStruct.st_mode) ){
string check = dptr->d_name;
if ( check.compare(".") == 0 || check.compare("..") == 0 ){
continue;
}
else{
cout << dptr->d_name << " is is a directory" << endl;
new_Directory.append("/");
new_Directory.append(dptr->d_name);
SearchDirectory(file_Name, new_Directory);
}
}
else if( S_ISREG(statStruct.st_mode)){
string check = dptr->d_name;
if( check.compare(file_Name) == 0){
cout << "Found " << file_Name << " in " << directory << "/" << endl;
}
}
}
}
int main(int argc, char *argv[]){
if(argc < 2 || argc > 2){
cerr << "This program will find the specified file." << endl;
cerr << "Usage: mysearch <filename>" << endl;
return 1;
}
string file_Name = argv[1];
SearchDirectory(file_Name, "/");
return 0;
}
POSIX.2 requires a working "find" command.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char **argv)
{
if (argc != 2) {
fprintf(stderr, "Usage: %s <filename>", argv[0]);
}
execlp("find", "find", "/", "-name", argv[1], "-print", (char *)NULL);
exit(EXIT_FAILURE);
}
->d_name returns just the name of the file, not the path to the file. You need to stat (not yet constructed) new_Directory instead of dptr->d_name.
You also have a problem if a directory contains more than one subdirectories. Your construction of new_Directory is incorrect for each subdirectory after the first.
You never closedir your directory handle, so you run out of resources. You should also consider loading the entire directory into an array before recursing to avoid running out of handles.
void SearchDirectory(string directory, string target_File_Name){
DIR *dirp = opendir(directory.c_str());
if (!dirp) {
perror(("opendir " + directory).c_str());
return;
}
struct dirent *dptr;
while(dptr = readdir(dirp)){
string file_Name = dptr->d_name;
string file_Path = directory + "/" + file_Name;
struct stat statStruct;
stat(file_Path.c_str(), &statStruct);
if( S_ISDIR(statStruct.st_mode) ){
if ( file_Name.compare(".") == 0 || file_Name.compare("..") == 0 ){
continue;
}
SearchDirectory(file_Path, target_File_Name);
}
else if( S_ISREG(statStruct.st_mode)){
if( file_Name.compare(target_File_Name) == 0){
cout << file_Path << endl;
}
}
}
closedir(dirp);
}
Update: Added second problem.
Update: Added third problem.
Update: Added code.
Not for the benefit of the OP, who writes "The point is to come up with a way to do it myself," but rather for the benefit of posterity, here is a way to use Boost.Filesystem:
#include <boost/filesystem.hpp>
namespace fs = boost::filesystem;
// sample usage: find_file("/home", ".profile");
void find_file( const fs::path& dirPath, const std::string& fileName) {
fs::recursive_directory_iterator end;
for(fs::recursive_directory_iterator it(dirPath); it != end; ++it) {
if(it->leaf() == fileName)
std::cout << it->path() << "\n";
if(fs::is_symlink(it->symlink_status()))
it.no_push();
}
}
Use fork, execv and the Unix implemented /usr/bin/find process and redirect its output for your result area?
I'm not sure if it's POSIX or not but the nftw library function is widely available on UNIX (HP-UX, AIX, Linux).
Your problem is "search a tree for a match"
BFS and DFS are the canonical basic algorithms. Give them a start node and go.
You will get into trouble if you follow symlinks; so test for them and don't follow them.
You should be able to map each point in the *FS algorithms to a directory operation.
Since C++ is an option, why not use something like Boost.Filesystem? The Boost.Filesystem two-minute tutorial gives an example of how to implement your search using directory iterators.
I've got a pretty basic console program here, to determine if a folder or file exists or not using stat:
#include <iostream>
#include <sys/stat.h>
using namespace std;
int main() {
char path[] = "myfolder/";
struct stat status;
if(stat(path,&status)==0) { cout << "Folder found." << endl; }
else { cout << "Can't find folder." << endl; } //Doesn't exist
cin.get();
return 0;
}
I have also tried the access version:
#include <iostream>
#include <io.h>
using namespace std;
int main() {
char path[] = "myfolder/";
if(access(path,0)==0) { cout << "Folder found." << endl; }
else { cout << "Can't find folder." << endl; } //Doesn't exist
cin.get();
return 0;
}
Neither of them find my folder (which is right there in the same directory as the program). These worked on my last compiler (the default one with DevCpp). I switched to CodeBlocks and am compiling with Gnu GCC now, if that helps. I'm sure it's a quick fix - can someone help out?
(Obviously I'm a noob at this so if you need any other information I've left out please let me know).
UPDATE
The problem was with the base directory. The updated, working program is as follows:
#include <iostream>
#include <sys/stat.h>
using namespace std;
int main() {
cout << "Current directory: " << system("cd") << endl;
char path[] = "./bin/Release/myfolder";
struct stat status;
if(stat(path,&status)==0) { cout << "Directory found." << endl; }
else { cout << "Can't find directory." << endl; } //Doesn't exist
cin.get();
return 0;
}
ANOTHER UPDATE
Turns out that a trailing backslash on the path is big trouble.
Right before your stat call, insert the code:
system("pwd"); // for UNIXy systems
system("cd"); // for Windowsy systems
(or equivalent) to check your current directory. I think you'll find it's not what you think.
Alternatively, run the executable from the command line where you know what directory you're in. IDEs will frequently run your executable from a directory you may not expect.
Or, use the full path name so that it doesn't matter which directory you're in.
For what it's worth, your first code segment works perfectly (gcc under Ubuntu 10):
pax$ ls my*
ls: cannot access my*: No such file or directory
pax$ ./qq
Cannot find folder.
pax$ mkdir myfolder
pax$ ll -d my*
drwxr-xr-x 2 pax pax 4096 2010-12-14 09:33 myfolder/
pax$ ./qq
Folder found.
Are you sure that the current directory of your running program is what you expect it to be? Try changing path to an absolute pathname to see if that helps.
Check your PWD when you running your program. This problem is not caused by compiler. You DevCpp may set a working directory for your program automatically.
You can find out why stat() failed (which is a C function, not C++, by the way), by checking errno:
#include <cerrno>
...
if (stat(path,&status) != 0)
{
std::cout << "stat() failed:" << std::strerror(errno) << endl;
}
Changing a Linux C++ program which gives the user limited file access. Thus the program chroots itself to a sandbox with the files the user can get at. All worked well.
Now, however, the program needs to access some files for its own needs (not the user's) but they are outside the sandbox. I know chroot allows access to files opened before the chroot but in this case the needed files could a few among many hundreds so it is obviously impractical to open them all just for the couple that might be required.
Is there any way to get at the files?
Copy them into the sandbox or open them all before chrooting. Seriously. If there was a way to do this, there would be a way to suborn it to allow other access and make your protection useless.
The whole point of the sandbox is to prevent exactly what you're trying to achieve.
If the files are all in 1 directory, you could use mount to bind them to a directory inside the sandbox.
mount --bind /path/to/files /sandbox/files
The you can access the files through /sandbox/files/. If you don't want the user to see them, do mount --bind /path/to/files /sandbox/.files so the .files directory is hidden
I guess that you ought to be able to split your program into two parts, one which is chroot'ed and one which isn't, and have the chroot'ed portion request files' contents from the non-chroot'ed portion via the IPC mechanism of your choice.
This is a hack, and it may be easy to get wrong, negating any benefit of a chroot. Like paxdiablo says, you're trying to get around the whole purpose of a chroot sandbox, so your options are very, very limited.
Maybe if you explained a bit more what you're trying to accomplish, we might be able to offer some other ideas. For example, SELinux and AppArmor are more flexible than chroot and may be able to give you the security you seek.
If the files you need to access are within a few directories you could open those directories before you chroot and save the file descriptors. You can then use the so-called *at functions (e.g. openat(), renameat(), etc.) to get at the individual files. Basically you are opening the files relative to the already open directory file descriptors rather than the chrooted directory.
Whether this is a safe thing to do is open to question but it should work in Linux.
EDIT: This is on the ugly side but it seems to work. You should poke around a lot more for vulnerabilities than I have. I haven't tested how dropping privileges and so forth will effect things.
#include <iostream>
#include <string>
using namespace std;
#include <cstdio>
#include <cstdlib>
#include <cerrno>
#include <cstring>
#include <unistd.h>
#include <fcntl.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
int main(int argc, char *argv[])
{
if (argc < 4)
{
cerr << "USAGE: " << argv[0] << " <jail directory> <freeworld directory> <filename>\n";
exit(EXIT_FAILURE);
}
const string JAILDIR(argv[1]);
const string FREEDIR(argv[2]);
string freefilename(argv[3]);
while (freefilename[0] == '/')
freefilename.erase(0, 1);
DIR *pDir;
if ((pDir = opendir(FREEDIR.c_str())) == NULL)
{
perror("Could not open outside dir");
exit(EXIT_FAILURE);
}
int freeFD = dirfd(pDir);
//cd to jail dir
if (chdir(JAILDIR.c_str()) == -1)
{
perror("cd before chroot");
exit(EXIT_FAILURE);
}
//lock in jail
if (chroot(JAILDIR.c_str()) < 0)
{
cerr << "Failed to chroot to " << JAILDIR << " - " << strerror(errno) << endl;
exit(EXIT_FAILURE);
}
//
//in jail, won't work
//
string JailFile(FREEDIR);
JailFile += "/";
JailFile += freefilename;
int jailFD;
if ((jailFD = open(JailFile.c_str(), O_RDONLY)) == -1)
{
cout << "as expected, could not open " << JailFile << endl;
perror("exected open fail");
}
else
{
cout << "defying all logic, opened " << JailFile << endl;
exit(EXIT_FAILURE);
}
//
//using this works
//
if ((jailFD = openat(freeFD, freefilename.c_str(), O_RDONLY)) == -1)
{
cout << "example did not work. Could not open " << freefilename << " Sorry!" << endl;
exit(EXIT_FAILURE);
}
else
cout << "opened " << freefilename << " from inside jail" << endl;
char buff[255];
ssize_t numread;
while (1)
{
if ((numread = read(jailFD, buff, sizeof(buff) - 1)) == -1)
{
perror("read");
exit(EXIT_FAILURE);
}
if (numread == 0)
break;
buff[numread] = '\0';
cout << buff << endl;
}
return 0;
}
To test:
echo "Hello World" >/tmp/mystuff.dat
mkdir /tmp/jail
sudo ./myprog /tmp/jail /tmp mystuff.dat
I'm trying to use the ofstream class to write some stuff to a file, but all that happens is that the file gets created, and then nothing. I have some simply code here:
#include <iostream>
#include <fstream>
#include <cstring>
#include <cerrno>
#include <time.h>
using namespace std;
int main(int argc, char* argv[])
{
ofstream file;
file.open("test.txt");
if (!file) {
cout << strerror(errno) << endl;
} else {
cout << "All is well!" << endl;
}
for (int i = 0; i < 10; i++) {
file << i << "\t" << time(NULL) << endl;
}
file.flush();
file.close();
return 0;
}
When I create a console application, everything works fine, so I'm afraid this code is not completely representative. However, I am using code like this in a much larger project that - to be honest - I don't fully understand (Neurostim). I'm supposed to write some class that is compiled to a dll which can be loaded by Neurostim.
When the code is run, "test.txt" is created and then "No error!" is printed, as this is apparently the output from strerror. Obviously this is wrong however. The application runs perfectly otherwise, and is not phased by the fact that I'm trying to write to a corrupted stream. It just doesn't do it. It seems to me like there is no problem with permissions, because the file is in fact created.
Does anyone have any ideas what kind of things might cause this odd behavior? (I'm on WinXP Pro SP3 and use Visual C++ 2008 Express Edition)
Thanks!
Just a thought :- in your real code are you re-using your stream object?
If so, you need to ensure that you call clear() on the stream before re-using the object otherwise, if there was a previous error state, it won't work. As I recall, not calling clear() on such a stream would result in an empty file that couldn't be written to, as you describe in your question.
ofstream file;
file.open("test.txt");
Just a nit: you can combine that into a single line. ofstream file("test.txt");
if (file) {
cout << strerror(errno) << endl;
} else {
cout << "All is well!" << endl;
}
Your test is backwards. If file is true, it's open and ready for writing.
Also, I wouldn't count on strerror() working correctly on Windows. Most Windows APIs don't use errno to signal errors. If your failure is happening outside the C/C++ run-time library, this may not tell you anything interesting.
UPDATE Thinking more about this, failing to open a file via fstreams is not guaranteed to set errno. It's possible that errno ends up set on some platforms (espeically if those platforms implement fstream operations with FILE* or file descriptors, or some other library that sets errno) but that is not guaranteed. The official way to check for failure is via exceptions, std::io_state or helper methods on std::fstream (like fail or bad). Unfortunately you can't get as much information out of std::streams as you can from errno.
You've got the if statement wrong. operator void* returns NULL (a.k.a. false) if the file is not writable. It returns non-zero (a.k.a. true) if the file is writeable. So you want:
if (!file) {
cout << strerror(errno) << endl;
} else {
cout << "All is well!" << endl;
}
Or:
if (!file.good()) {
cout << strerror(errno) << endl;
} else {
cout << "All is well!" << endl;
}