I am trying to use unistd.h write from inside a class where another "write" function has been declared, but I don't know which is the scope resolutor I should use, as unistd is not a library, so unistd::write() won't work.
How can I call it from inside the function?
// this won't compile
#include <stdio.h> // printf
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
class Fifo {
public:
void write(const char* msg, int len);
};
void Fifo::write(const char* msg, int len) {
int fd;
const char* filename = "/tmp/fifotest";
mkfifo(filename, 0666);
fd = open(filename, O_WRONLY|O_NONBLOCK);
write(fd, msg, len);
close(fd);
}
int main()
{
Fifo fifo;
fifo.write("hello", 5);
return 0;
}
So use the unnamed scope write
. The
write(fd, msg, len);
is equal to
this->write(fd, msg, len);
write
resolved to Fifo::write
inside Fifo
function. Do:
::write(fd, msg, len);
to use global scope. like:
#include <cstdio> // use cstdio in C++
extern "C" { // C libraries need to be around extern "C"
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
}
class Fifo {
public:
void write(const char* msg, int len);
};
void Fifo::write(const char* msg, int len) {
int fd;
const char* filename = "/tmp/fifotest";
mkfifo(filename, 0666);
fd = open(filename, O_WRONLY|O_NONBLOCK);
::write(fd, msg, len); //here
close(fd);
}
int main() {
Fifo fifo;
fifo.write("hello", 5);
return 0;
}
Research scopes, namespaces and scope resolution operator in C++ for more information.