Prevent opening file in "rw" and "r" at the same time - linux

I'm writing class to r/w files from OS file system or from my own archives format in my game engine. How can I make impossible to open file by std::fopen() or std::fstream in modes "rw" and "r". I have written some code to test that on Linux. Here's it:
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
fstream in("file.txt", ios::in | ios::out);
if(!in.is_open())
{
cout << "Plik nie może być otwarty w trybie rw" << endl;
return 1;
}
cout << "Plik otwarty w trybie rw" << endl;
in << ".test.";
cout << "Wpisano tekst" << endl;
while(1){}
return 0;
}
/* Drugi plik */
/* The second src code */
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
fstream in("file.txt", ios::in);
if(!in.is_open())
{
cout << "Plik nie może być otwarty w trybie r" << endl;
return 1;
}
cout << "Plik otwarty w trybie r" << endl;
cout << in << endl;
return 0;
}
When I've executed the ./rw program and some instances of ./r, the ./rw has gone into endless loop and the instances of ./r have terminated with 0 code.
Sorry for my English. :)

You should "lock" the file using lockf(): http://man7.org/linux/man-pages/man3/lockf.3.html

Related

this vector has vector probelem is not working

The problem is it prints the full name but not the rest of the lines about the person.
Could someone, please guide me?
I do really appreciate your help!
auto itr = find(my_vec.begin(), my_vec.end(), search );
if(itr != my_vec.end())
{
std::cout << "Match found " << search << std::endl;
std::cout << "\nFull name: " << search << std::endl;
} else {
std::cout << "Match not found "<< std::endl;
}
There are a few style problems with your code:
No need to explicitly initialize strings, they will be empty by default (see here).
Keep a consistent style. For example, either always start brackets in the same line as the function signature or in the next line.
No need to close the file explicitly at the end of the function, this is done when the object goes out of scope (see (destructor) here).
No need to include <map> and <iomanip> headers.
Don't keep unused variables.
Give suggestive names to your variables.
Do not return error codes to the OS when the app is working as it should. Not finding a name is not an error, is it?
It seems your file has 6 entries per contact, so all you have to do is print 5 more lines. You do not need to store the lines in a vector, just parse and print them as you go. Here is an example:
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <fstream>
void findContact(std::string fullName, std::string contactListPath) {
std::ifstream inFile{contactListPath};
if (!inFile) {
std::cerr << "File could not be open!" << std::endl;
return;
}
std::string line;
while (std::getline(inFile, line)) {
if (line == fullName) {
std::cout << "Match found: \n";
std::cout << "\nFull name: " << fullName;
std::cout << "\nAddress: " << (std::getline(inFile, line), line);
std::cout << "\nE-mail: " << (std::getline(inFile, line), line);
std::cout << "\nPhone: " << (std::getline(inFile, line), line);
std::cout << "\nBirthday: " << (std::getline(inFile, line), line);
std::cout << "\nNote: " << (std::getline(inFile, line), line) << std::endl;
return;
}
}
std::cout << "Match not found " << std::endl;
}
int main() {
std::string fullName;
std::string contactListPath;
std::cout << "Enter full name to search: ";
std::getline(std::cin, fullName);
std::cout << "Enter path to contact list: ";
std::getline(std::cin, contactListPath);
findContact(fullName, contactListPath);
return 0;
}
If every entry contains 6 lines. Then you can print all the lines starting from the line that you found like:
auto itr = find(my_vec.begin(), my_vec.end(), search );
if(itr != my_vec.end())
{
std::cout << "Match found " << std::endl;
// print the next 6 lines
for(int remaining = 6;remaining > 0 && itr!=my_vec.end(); itr++,remaining--) {
std::cout << *itr << std::endl;
}
} else {
std::cout << "Match not found "<< std::endl;
}

namespace std has no member image?

#include <chrono>
#include <algorithm>
#include <CL/sycl.hpp>
using namespace sycl;
using namespace std::chrono;
using namespace std;
#include <iostream>
#include <fstream>
#include <sstream>
static const int x = 250;
static const int y = 250;
int main()
{
queue q; //create queue
std::cout << "Device: " << q.get_device().get_info<info::device::name>() << std::endl;
std::ofstream image;
image.open("Saltpepper.pgm");
//while open
if (image.is_open()) {
//header info
image << "P3" << std::endl;
image << "250 250" << std::endl;
image << "255" << std::endl;
//to do parallel execution ?
q.parallel_for(range<1>(x), [=](id<1> i) {
std::image << (x * y) % 255 << " " << (x * y) % 255 << " " << (x * y) % 255 << std::endl;
}
std::image.close(); //
}
}
if u want to access your image file you can use them in the following manner
/ Data is array of floats
std::vector<float> v(10000);
// User defines new operator << for std::vector<float> type
std::ofstream& operator << (std::ofstream & str, std::vector<float> & vec)
{
// User’s output actions
...
}
...
// Output file declaration – object of standard ofstream STL class
std::ofstream external_file(“output.txt”);
...
// Output operations
external_file << v;
You can follow the below link for more reference
https://software.intel.com/content/www/us/en/develop/documentation/oneapi-dpcpp-cpp-compiler-dev-guide-and-reference/top/compiler-reference/libraries/intel-s-c-asynchronous-i-o-extensions-for-windows-operating-systems/intel-s-c-asynchronous-i-o-class-for-windows-operating-systems/example-for-using-async-class-template-class.html

ncurses nodelay for responsive arrow key feedback

I am trying to write integers to a file using ncurses and the keyboard arrows. I use nodelay so that I can write a 4 to the file while nothing is being pressed. ESC exits the program. The problem is that all I can ever write to the files is 4. ESC seems to work fine, so the switch is working. If I take out the nodelay the program works but 4 cannot ever be writen.
Thanks
#include <ncurses.h>
#include <fstream>
using namespace std;
int main(int argc, char* argv[])
{
ofstream outFile;
char outputFilename[80];
sprintf(outputFilename, "files/file.%s",argv[1]);
outFile.open(outputFilename, ios::out);
int ch;
initscr();
nodelay(stdscr,TRUE);
raw();
keypad(stdscr, TRUE);
noecho();
refresh();
while(1){
ch = getch();
switch(ch)
{
case KEY_UP:
outFile << 0 << endl;
break;
case KEY_DOWN:
outFile << 1 << endl;
break;
case KEY_RIGHT:
outFile << 2 << endl;
break;
case KEY_LEFT:
outFile << 3 << endl;
break;
case ERR:
outFile << 4 << endl;
break;
case 27:
outFile.close();
endwin();
return 0;
break;
default:
break;
}
refresh();
}
}
I was able to fix this issue by checking to see if the last value of ch was ERR before writing 4 to the file. Not sure I understand completely... maybe a timing issue. New program:
#include <ncurses.h>
#include <fstream>
using namespace std;
int main(int argc, char* argv[])
{
ofstream outFile;
char outputFilename[80];
sprintf(outputFilename, "interactive/taker.%s",argv[1]);
outFile.open(outputFilename, ios::out);
int ch;
int ch_prev=0;
initscr();
nodelay(stdscr,TRUE);
raw();
keypad(stdscr, TRUE);
noecho();
while(1){
ch = getch();
switch(ch)
{
case KEY_UP:
outFile << 0 << endl;
break;
case KEY_DOWN:
outFile << 1 << endl;
break;
case KEY_RIGHT:
outFile << 2 << endl;
break;
case KEY_LEFT:
outFile << 3 << endl;
break;
case ERR:
if (ch_prev != ERR)
outFile << 4 << endl;
break;
case 27:
outFile.close();
endwin();
return 0;
break;
default:
break;
}
ch_prev=ch;
refresh();
}
}
Without the check, you will overlook the lines which are not 4's, since almost all of the return values are ERR's. Also - the program will be using a lot of CPU (doing nothing). You would get better results if you used timeout with a fairly short value (10-50 milliseconds) rather than nodelay.

Why this small c++11 multi threaded program giving segmentation fault

why this program giving seg fault. I tried figuring out the issue using gdb, but no luck.
#include <iostream>
#include <condition_variable>
#include <thread>
#include <chrono>
using namespace std;
condition_variable cv;
mutex cv_m;
mutex m;
int count = 0;
#define COUNT_DONE 10
#define COUNT_HALT1 3
#define COUNT_HALT2 6
void functionCount1()
{
for(;;)
{
m.lock();
count++;
cout << "Counter value functioncount1: " << count << endl;
m.unlock();
if(count >= COUNT_DONE)
return;
}
}
void functionCount2()
{
for(;;)
{
m.lock();
count++;
cout << "Counter value functionCount2: " << count << endl;
m.unlock();
if(count >= COUNT_DONE) return;
}
}
int main()
{
thread t1(functionCount1), t2(functionCount2);
t1.join();
t2.join();
return 0;
}
Your program has undefined behavior: the accesses to count outside the mutex in functionCount1 and functionCount2 are data races. With the UB corrected, it seems fine:
#include <iostream>
#include <mutex>
#include <thread>
using namespace std;
mutex m;
int count = 0;
#define COUNT_DONE 10
void functionCount(const char* name)
{
for(;;)
{
m.lock();
auto c = ++count;
m.unlock();
cout << "Counter value " << name << ": " << c << endl;
if(c >= COUNT_DONE)
return;
}
}
int main()
{
thread t1(functionCount, "functionCount1"), t2(functionCount, "functionCount2");
t1.join();
t2.join();
}
or if you want to be "clever" and confuse your code reviewers:
void functionCount(const char* name)
{
for(;;)
{
auto c = (std::lock_guard<std::mutex>(m), count++);
cout << "Counter value " << name << ": " << c << endl;
if(c >= count_done)
break;
}
}

How to enter 'quit' to close program?

How do I instead of entering a name, enters 'quit' and it will close the program?
string name;
cout << "Enter a name: "<< " ";
std::getline (std::cin,input);
input[0] = toupper (input[0]);
C++ is rusty something like this...
string name;
cout << "Enter a name: "<< " ";
std::getline (std::cin,input);
input[0] = toupper (input[0]);
if (input[0] == 'quit')
{
std::exit;
}
Using Visual C++
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
int main(int argc, char* argv[])
{
string strinput;
while (strinput != "quit")
{
cout << "Enter a name: " << endl;
cin.clear();
cin >> strinput;
if(strinput =="quit")
exit(0);
}
return 0;
}

Resources