How to delete a file in file handling in c++ - c++

i made a function that first reads the file and checks if it exists or not and then it removes it after a confirmation but if i do directly like
remove("a.text");
it deletes the file that has the name a.txt but when i use my function
int deletediary()
{
string searchfilename;
cout<<"\nPlease enter the filename to be searched\n";
cin>>searchfilename;
searchfilename.append(".txt");
fileread.open(searchfilename.c_str());
if(!fileread){
cout<<"\nERROR :Either you didn't enter an invalid date or you entered an date with no entry\n\n";
A :
cout<<"Continue to search? (y/n)\n";
if(getch()=='y')
{
modifydiary();
}
else if(getch()=='n')
{
menuview();
}
else
{
cout<<"Enter Correct Option\n";
goto A;
}
}
else{
system("cls");
int i;
B :
cout<<"Are you sure you want to remove this diary entry? (y/n)";
if(getch()=='y')
{
remove(searchfilename.c_str());
}
else if(getch()=='n')
{
menuview();
}
else
{
cout<<"Enter Correct Option\n";
goto B;
}
cout<<"INFO :Deleted!!!";
system("pause");
menuview();
}
it only checks the filename but does not delete it.

In c++17 we have the filesystem library, which gives the tools to easily deal with the problem.
Example:
#include <filesystem>
#include <iostream>
#include <string>
int main()
{
std::string searchfilename;
std::cout << "Please enter the filename to be searched\n";
std::cin >> searchfilename;
try {
if (std::filesystem::remove(searchfilename))
std::cout << "file " << searchfilename << " deleted.\n";
else
std::cout << "file " << searchfilename << " not found.\n";
}
catch(const std::filesystem::filesystem_error& err) {
std::cout << "filesystem error: " << err.what() << '\n';
}
}

You forgot closing the file that you have opened.
So, CLOSE the file and it should work.
Note: The solution worked for #AkhileshSharma and included the comment as an answer to close the question as answered.

When you try to delete a file, you should always handle the return value of remove function immediately. For successful result it returns 0 and for failed, it returns non-zero.
const int result = remove( "no-file" );
if( result == 0 ){
printf( "success\n" );
} else {
printf( "%s\n", strerror( errno ) ); // No such file or directory
}
remove is in the stdio.h file
and strerror is in the string.h
So after your remove function, check to see for what reason it has not been deleted.
The error number is stored in errno variable and strerror can map the error number to a string that tells the reason of failure.
Also you can test the error code and a Linux Terminal if you have it using perror command
> perror 0
OS error code 0: Success
> perror 1
OS error code 1: Operation not permitted
> perror 2
OS error code 2: No such file or directory
> perror 3
OS error code 3: No such process
> perror 4
OS error code 4: Interrupted system call
> perror 5
OS error code 5: Input/output error

//you have to give the path of the file for example(path="C:\\data\\newfolder")
System::IO::DirectoryInfo^ directory = gcnew System::IO::DirectoryInfo(path);
for each(System::IO::FileInfo^ file in directory->GetFiles())
{
//for getting the extension of file(if you want to delete specific extension file)
String^ s = file->Extension;
if (file->Extension == ".png")
{
file->Delete();
}
}

Related

How do I handle empty files when dumping ifstream to cout?

I'm trying to dump the contents of a file to cout.
#include <iostream>
#include <fstream>
int main(int argc, char** argv)
{
if (argc > 1) {
std::ifstream fin(argv[1]);
if (fin) {
std::cout << "---file contents---\n";
std::cout << fin.rdbuf();
std::cout << "---end contents---\n";
} else {
std::cout << "The file does not exist\n";
}
}
else {
std::cout << "Usage: " << argv[0] << " FILE\n";
}
if (std::cout.good()) {
return 0;
}
else if (std::cout.fail()) {
return 1;
}
else {
return 2;
}
}
This code does not work as intended when the input file is empty. It prints the initial "---file contents---", but never prints the trailing "---end contents---". After debugging, I found the application is not crashing, but instead is putting std::cout in an error state (the return code is 1).
How can I print the contents of an empty file without putting cout in an error state?
This operator<< reference (overload number 10 in the list) explains it all:
If no characters were inserted, executes setstate(failbit).
Since the input file is empty, there's no characters to insert into the output stream. And the failbit is set.
You need to add a specific check for failbit after
std::cout << fin.rdbuf();
to see if the input file was empty or not.

c++ - _mkdir giving false errors windows

Hi I am trying to make a directory in windows with this code
header
#include <direct.h>
script
int main() {
string local = "C:/Program Files (x86)/Mail";
try
{
_mkdir (local.c_str ());
cout << "It is made?";
}
catch(invalid_argument& e)
{
cout << e.what () << " " << (char*) EEXIST;
if (e.what () == (char*) EEXIST) {
cout << e.what () << " " << (char*) EEXIST;
}
return;
}
}
The file is clearly not made, but it is also not making the error it should.
_mkdir won't throw an exception. (This is not python or boost, or any smart middleware)
Read the documentation you were referring to: it returns a value. 0 is OK, -1: error, ask why to errno
Don't ignore the return value. You probably have insufficient rights without UAC elevation to create the directory.
So I finally figured errno out, which for errno you need the <errno.h> header. The complete list of errno codes.
If you want to see what errno code something is throwing lets say
if (
_mkdir(((string)"C:/Program Files (x86)/Mail").c_str()) == 0 ||
errno == 17 /* this is the code for - File exists - */
){
// Do stuff
} else {
int errorCode = errno; // You need to save the code before anything else,
// because something else might change its value
cout << errorCode;
}

is it possible to grab data from an .exe file in c++?

I am new at C/C++,
So basically I want to call an .exe file that displays 2 numbers and be able to grab those two numbers to use them in my code.
To call the .exe file I've used the system command, but I am still not able to grab those two numbers that are displayed by the .exe file
char *files = "MyPath\file.exe";
system (files);
I think this is better aproach:
Here you just create new process, and you read data that process gives you. I tested this on OS X 10.11 with .sh file and works like a charm. I think that this would probably work on Windows also.
FILE *fp = popen("path to exe","r");
if (fp == NULL)
{
std::cout << "Popen is null" << std::endl;
}else
{
char buff[100];
while ( fgets( buff, sizeof(buff), fp ) != NULL )
{
std::cout << buff;
}
}
You need to escapr back slashes in C++ string literals so:
// note the double "\\"
char* files = "MyPath\\file.exe";
Or just use forward slashes:
char* files = "MyPath/file.exe";
Its not very efficient but one thing you can to with std::system is redirect the output to a file and then read the file:
#include <cstdlib>
#include <fstream>
#include <iostream>
int main()
{
// redirect > the output to a file called output.txt
if(std::system("MyPath\\file.exe > output.txt") != 0)
{
std::cerr << "ERROR: calling system\n";
return 1; // error code
}
// open a file to the output data
std::ifstream ifs("output.txt");
if(!ifs.is_open())
{
std::cerr << "ERROR: opening output file\n";
return 1; // error code
}
int num1, num2;
if(!(ifs >> num1 >> num2))
{
std::cerr << "ERROR: reading numbers\n";
return 1; // error code
}
// do something with the numbers here
std::cout << "num1: " << num1 << '\n';
std::cout << "num2: " << num2 << '\n';
}
NOTE: (thnx #VermillionAzure)
Note that system doesn't always work everywhere because unicorn
environments. Also, shells can differ from each other, like cmd.exe
and bash. – VermillionAzure
When using std::system the results are platform dependant and not all shells will have redirection or use the same syntax or even exist!

File not opening with C++ fstream even with full path

string mapFile;
cout << "Enter the file name : ";
cin >> mapFile;
ifstream mapfh;
mapfh.open(mapFile.c_str());
if(mapfh.is_open()) { ... }
else //if board file did not open properly
{
throw;
}
mapfh.close();
I am compiling with g++ in the command line. Whenever I put a file input (even with a full path i.e. /User/...etc./file.txt) it throws an error. I know the input is good, but for whatever reason the open always fails.
This isn't fully portable, but you'll get a more informed output if you interpret the errno,
#include <cerrno>
#include <cstring>
...
if(mapfh.is_open()) { ... }
else //if board file did not open properly
{
std::cout << "error: " << strerror(errno) << std::endl;
throw;
}
And if your policy is to communicate the errors as exceptions then use iostreams native support for the exceptions:
ifstream mapfh;
mapfh.exceptions(std::ios::failbit);
try {
mapfh.open(mapFile.c_str());
...
mapfh.close();
} catch (const std::exception& e) {
std::cout << e.what() << " : " << std::strerror(errno) << std::endl;
}

How to log all input (cin) into file in C++

Actually, I'm working on a minishell. My functions work, but when I want to log the whole cin stuff (commands, parameters, output) into a file, nothing appears in the file. Nowhere can I find something to handle with full input and output with parameters.
I hope someone can help me.
My code:
using namespace std;
ofstream outputFile;
void read_command(char *com, char **par){
fprintf(stdout, "$");
cin >> com;
outputFile.open("logging.txt"); // file opened but nothing APPEARS IN IT????
if(strcmp(com,"date")== 0){ // DATE
time_t rawtime;
time ( &rawtime );
printf ( "%s", ctime (&rawtime) );
}
else if(strcmp(com,"echo")== 0) // ECHO
{
string echo_part;
cin >> echo_part;
cout << echo_part << endl;
}
else if(strcmp(com,"sleep")== 0){ // SLEEP
int howlong = 0;
cin >> howlong;
cout << "seconds: " << howlong << "....zZZzzZzz" << endl;
sleep(howlong);
}
else if(strcmp(com,"ps")== 0) // PROCESS
{
execlp("/bin/ps","ps","-A",NULL); // ps - command
}
}
void handler(int p) { // CTR-C handler
cout << endl;
cout << "Bye !" << endl;
outputFile.close();
alarm(1); // 2 seconds alarm ends process with kill
}
int main(){
int childPid;
int status;
char command[20];
char *parameters[60];
signal(SIGINT,&handler); // CTR-C exit disabled
while (1) {
read_command(command, parameters);
if ((childPid = fork()) == -1) {
fprintf(stderr,"can't fork\n");
exit(1);
}
else if (childPid == 0) { //child
execv(command, parameters);
exit(0);
}
else { // parent process
wait(&status);
}
}
}
You re-open the output stream outputFile for every line, overwriting the file with each new command.
Edit: As the other posters noted, not actually writing something to outputFile might be a second reason.
You open outputFile, but never write anything to it. What should appear there?
To output something to the file, try
outputFile << something
there are no
outputFile << ...;
so you are not writing to the file
Your code contains a lot of potential memory access violations.
There are libraries to help you in what you are trying to do (reading and interpreting user input), for instance the GNU Readline library, which is coded in C (but can be used by C++ code, as is the case for all the C-written libraries).
There are some nice C++ wrappers, such as for instance SReadlineWrapper.