Cannot open file /sys/class/net/eth0/carrier - c++

I have following function isEthernetCableConnected() which I am calling in a thread in continuous loop. After a long time I started to get log "Could not open /sys/class/net/eth0/carrier". How can it be possible? If it is possible then please give me some idea how to open the file every time.
ETH_FILE_CARRIER /sys/class/net/eth0/carrier
int isEthernetCableConnected(){
FILE *fp = fopen(ETH_FILE_CARRIER, "r");
int result;
if(fp == NULL) {
CLog::getInstance()->error("utility",__LINE__,__FILE__,"networked::isEthernetConnected, Could not open %s", ETH_FILE_CARRIER);
return 0;
}
fscanf(fp,"%d",&result);
fclose(fp);
return result;
}

Please refer the below link, it might help you
http://wikistack.com/how-to-check-if-ethernet-cable-is-connected-linux
In this link, they are trying to open the file in different way. May be you can try that.

Related

Reading txt file in Visual studio 2019 C++

I am trying to open a file for this program. I have tried pathing it directly using examples like C:\User... but for some reason it still says it can't find the file. I have looked on the internet as well as youtube to open files using C++ and its pretty straight forward. However I still can't get this .txt file to be read. Maybe it has to do with Visual Studio?
FILE* in_fp, * fopen();
int main() {
if ((in_fp = fopen("TextFile.txt", "r")) == NULL)
printf("ERROR - cannot open front.in \n");
else
{
getChar();
do {
lex();
} while (nextToken != EOF);
}
}

fopen / ofstream::open fail when creating a BMP file

Years ago I created a C++ function using FILE to create bitmap files. Recently (not sure when or why) this code is now failing when opening the file. The problem is with the open call ...
file_ptr = fopen("ScreenShots/Screenshot1.bmp", "wb");
Currently this results in an error 13, permission denied error. Change the filename extension to something else and the fopen works fine. For example,
file_ptr = fopen("ScreenShots/Screenshot1.bm2", "wb");
The file saves correctly and when changing the extension back to BMP I can display the file correctly in Paintshop.
Did a quick check using ofstream and same problem.
Any ideas why I get a permission denied error when trying to open BMP files to write data? For information I am using Visual Studio Community 2017 on Windows 10.
To give the complete section of code ...
BITMAPFILEHEADER bitmap_header;
BITMAPINFOHEADER bitmap_info;
FILE *file_ptr;
unsigned int count;
unsigned char tempRGB;
char filename[256];
bool finished;
// CREATE A UNIQUE FILENAME
count = 1;
finished = false;
do
{
// CREATE NAME
sprintf(filename, "ScreenShots/Screenshot%d.bmp", count);
// CHECK IF FILE EXISTS
errno = 0;
file_ptr = fopen(filename, "rb");
if (file_ptr)
{
// FILE EXISTS
fclose(file_ptr);
count = count + 1;
}
else
{
// UNIQUE FILENAME
file_ptr = fopen(filename, "wb");
if (file_ptr == NULL)
{
// UNABLE TO OPEN FOR WRITING - GIVE UP
// (USING OWN LOGGING CLASS)
jalog.log("\nERROR on Screenshot >");
jalog.log(filename);
jalog.log("< >");
jalog.log((short)errno);
return;
}
finished = true;
}
}
while (finished == false);
I've managed to find the issue ... Avast antivirus. I noticed that trying to do an open action for a BMP file took a few seconds while opening any other file type (successfully or unsuccessfully) was instantaneous. As something similar happens when running new programs I tried disabling all the Avast shields and I could successfully create a BMP file using the existing code.
For my own personal use I can whitelist my own programs, but annoying if I get to distributing the program to other people.
Thanks for the help ... and sorry for raising a C++ issue that in the end had nothing to do with C++!

A way to know if the file currently is open before open it again?

I have a program which opens the same file several times.
I want to check before open any file if this file currently is open or not because I don't want to open the same file several times.
Is there a built-in function which can check if the file is currently open or any other way can do that?
The Code:
QString openFilePath = QFileDialog::getOpenFileName(this->mainWindow, "Open File");
if(openFilePath == ""){
return;
}
QFile openFile(openFilePath);
if(!openFile.open(QFile::ReadWrite)){
QMessageBox::critical(this->mainWindow, "Can't Open file", "Can't access to the file.");
}
QTextStream fileContent(&openFile);
QFileInfo fileInfo(openFile);
this->createEmptyFile(fileInfo.fileName());
this->txtEditor->setText(fileContent.readAll());
It seems to me that your question has really nothing to do with file opening in the programmatic sense, but is exclusively related to your application logic. You need to internally keep a list of all currently open files (in the sense that your GUI is showing such file), and do a check if the user opens a new file.
existing question
also you can try the hack) I dont know would it works or not, but: in the
void QFile::setFileName(const QString &name)
function overview QFile you can see that
Do not call this function if the file has already been opened.
Hmm) what if try to rename it in try catch to avoid crashing and if the renaming done, rename it again and open?) so you can try.
Regular file open, say for append, depending on the function, will usually return NULL or raise an exception if the file is already open. There are stateless file systems where this approach may not work.
std::fstream fs;
try {
fs.open("lk.txt", std::fstream::in | std::fstream::out | std::fstream::app);
fs << "We're way beyond the boundaries of the Pride Lands.";
} catch (const std::ios_base::failure &ex) {
// Something happened
std::cerr << ex.what() << std::endl;
}
fs.close();
In some file systems there are also shared open modes, which will explicitly let you concurrently reopen the file and do what you want with no errors generated.
here is the solution to your problem:-
is_open()
Scope:
std::ofstream::is_open
1.it Check if file is open or not?
2.it returns whether the stream is currently associated to a file
3.it is public member function of fstream.
4.parameters -none
Sample Code:
#include <iostream>
#include <fstream> // std::ofstream
int main ()
{
std::ofstream ofs;
ofs.open ("hye.txt");
if (ofs.is_open())
{
ofs << "hellow world";
cout << "successfully written to file";
ofs.close();
}
else
{
cout << "Error opening file";
}
return 0;
}
output:
successfully written to file

Creating text file into C++ addon of node.js

I want to know how i can create file and append data inside it in c++ addon (.cc) file of node.js ??
I have used below code to do same, but not able to find file "data.txt" in my ubuntu machine(reason behind it may be below code is not correct way to create file, but strange i haven't received any error/warning at compile time).
FILE * pFileTXT;
pFileTXT = fopen ("data.txt","a+");
const char * c = localReq->strResponse.c_str();
fprintf(pFileTXT,c);
fclose (pFileTXT);
Node.js relies on libuv, a C library to handle the I/O (asynchronous or not). This allows you to use the event loop.
You'd be interested in this free online book/introduction to libuv: http://nikhilm.github.com/uvbook/index.html
Specifically, there is a chapter dedicated to reading/writing files.
int main(int argc, char **argv) {
// Open the file in write-only and execute the "on_open" callback when it's ready
uv_fs_open(uv_default_loop(), &open_req, argv[1], O_WRONLY, 0, on_open);
// Run the event loop.
uv_run(uv_default_loop());
return 0;
}
// on_open callback called when the file is opened
void on_open(uv_fs_t *req) {
if (req->result != -1) {
// Specify the on_write callback "on_write" as last argument
uv_fs_write(uv_default_loop(), &write_req, 1, buffer, req->result, -1, on_write);
}
else {
fprintf(stderr, "error opening file: %d\n", req->errorno);
}
// Don't forget to cleanup
uv_fs_req_cleanup(req);
}
void on_write(uv_fs_t *req) {
uv_fs_req_cleanup(req);
if (req->result < 0) {
fprintf(stderr, "Write error: %s\n", uv_strerror(uv_last_error(uv_default_loop())));
}
else {
// Close the handle once you're done with it
uv_fs_close(uv_default_loop(), &close_req, open_req.result, NULL);
}
}
Spend some time reading the book if you want to write C++ for node.js. It's worth it.

Load the output of another command line program into mine

Ok suppose I have a program ( in windows a .exe file ) and when I run it, it outputs some information... now I'm writing another program ( in c++ ) and I need it to automatically run that .exe file and read the output so that it can process that information for further actions...
what should I do ?
Use popen or on windows (per comment) _popen. Basically it functions as the thing behind the | in some program | thing.
Normally I'm against posting complete code but I literally wrote this today and have it on hand, so, here you go. From what I understand C++ doesn't have a great interface that replaces popen but if you're bringing in the boost libraries or something at that layer there are solutions.
Note I use char[10] because in my application I know the output will be that short.
PopenWrapper(const std::string& command) {
fd = popen(command.c_str(), "r");
if(fd == NULL) {
throw PopenException("Failed to open command: " + command);
}
}
std::string get() {
char line[10];
fgets(line, sizeof(line), fd);
return std::string(line);
}
~PopenWrapper() {
if(fd != NULL) {
pclose(fd);
}
}