File permission error

I wrote a piece of code to find out the ipaddress of my linux machine. It works well when I compile it and run it in /tmp directory. But when I convert it to a binary using makefile, put it in /usr/sbin directory and run it, Im getting the following error.

sh: myip.txt: Permission denied
awk: (FILENAME=- FNR=1) warning: error writing standard output (Broken pipe)

Below is my code. Im using this peice of code in one of my helper processes for squid proxy. I have set the permissions for the myip.txt file in /usr/sbin/myip.txt using chmod 777 /usr/sbin/myip.txt.
Im still wondering why Im getting this permission denied error.

Below is my code.

#include<iostream>
#include<fstream>
#include<stdlib.h>
using namespace std;

int main(int argc, char **argv)
{

string ip_addr;
ifstream readFile;

readFile.open("myip.txt", ifstream::out);
system("ifconfig | grep 172 | awk {'print $2'}| sed s/.*:// > myip.txt");
readFile.close();

readFile.open("myip.txt", ifstream::in);
while(!readFile.eof()) {

readFile >> ip_addr;
}
readFile.close();

cout << ip_addr << "\n";
}

Help is highly appreciated!!
[code] "Please use code tags" [/code]
Long shot
1
2
ifstream readFile;
readFile.open("myip.txt", ifstream::out); //ifstream is only for input 


However why don't just use a script?
Also tail --lines=N will show you the last N lines

Edit: Another thing could be that the environment of the program is not what you think
try std::cout << getenv("PWD") << std::endl;

You could change the directory too. Either /tmp/ or /$home/.myip.txt
Last edited on
In your code:
1
2
3
readFile.open("myip.txt", ifstream::out);
system("ifconfig | grep 172 | awk {'print $2'}| sed s/.*:// > myip.txt");
readFile.close();
the readFile stuff is completely redundant. In fact, all the C++ is redundant.

It's the shell commands that are creating myip.txt (in the current directory). Why not write it to /tmp?

Topic archived. No new replies allowed.