<分区>
有什么方法/函数可以与 int file = open(filepath, flag);
一起使用吗?因为我正在尝试实现 flock
因为ifstream file; file.open("filepath");
不适用于 flock()
?
我正在尝试学习如何实现 flock()
在 C++ 中,我在网上找到了一些例子。这是我写的:
int file;
char configPath[] = "data/configuration.txt";
file = open(configPath, O_RDONLY);
if(file != -1) {
std::cout<<"Successfully opened file: "<<configPath<<std::endl;
if(flock(file,1) == 0) {
//do things with the file
}
}
但现在我不知道如何处理该文件。 我想逐行获取内容。
这是我之前的做法:
int readConfig(std::ifstream& configFile, std::string (&string)[10], int counter) {
std::cout<<"void readConfiguration\n";
if(!configFile) {
std::cout<<"configuration.txt couldn't be opened\n";
} else {
// Get content line by line of txt file
int i = 0;
while(getline(configFile,string[i++]));
//for debug only
for(int k = 0; k<i; k++) std::cout<<"string[k]= "<<string[k]<<"\n";
}
return counter;
}
configFile.open("data/configuration.txt");
std::string inputs[10];
int counter;
readConfig(configFile, inputs, counter);
但我不能使用flock()
当我使用 std::ifstream::open()
打开文件时因为flock()
需要两个 ints
作为参数:
extern int flock (int __fd, int __operation) __THROW;
编辑:
这是我在@MSalters 的帮助下得出的结论:
int readConfig(std::istream& configFile, std::string (&string)[10], int counter) {
std::cout<<"void readConfiguration\n";
if(!configFile) {
std::cout<<"configuration.txt couldn't be opened\n";
} else {
// Get content line by line of txt file
int i = 0;
while(getline(configFile, string[i++]));
//for debug only
for(int k = 0; k<i; k++) std::cout<<"string[k]= "<<string[k]<<"\n";
counter = i;
}
return counter;
}
int main()
{
int file;
char configPath[] = "data/configuration.txt";
file = open(configPath, O_RDONLY);
if(file != -1) {
std::cout<<"Successfully opened file: "<<configPath<<std::endl;
if(flock(file,1) == 0) {
__gnu_cxx::stdio_filebuf<char> fd_file_buf{file, std::ios_base::out | std::ios_base::binary};
std::istream fd_stream{&fd_file_buf};
std::string inputs[10];
int counter;
readConfig(fd_stream, inputs, counter);
flock(file,8);
file = close(file);
}
}
}
它编译并运行,但是std::cout<<"string[k]= "<<string[k]<<"\n";
返回 string[k]=
就是这样。
编辑2:
我有一个用 PHP 编写的网页,使用户能够输入 6 个值:
URL
URL Refresh Interval
Brightness
Color1 in hex
Color2 in hex
Color3 in hex
这些值将写入configuration.txt
.
每次访问网页configuration.txt
打开后,PHP 从那里获取一些值,然后将其关闭。
configuration.txt
当提交上述一个或多个值时也会打开,然后关闭。
接下来,我有一个定期 wgets
的 bash来自 configuration.txt
的 URL并将输出写入另一个名为 url_response.txt
的文件.
while [ 0 ]
do
line=$(head -n 1 data/configuration.txt)
wget -q -i $line -O url_response.txt
sleep 2
done
此脚本将被放入 C++ 程序中。
最后,同一个 C++ 程序必须访问 url_response.txt
从中获取和解析一些字符串,它还必须访问 configuration.txt
从中获取三种颜色。
所以我想实现flock()
在所有这些程序中。
一切都将在运行 Linux raspberrypi 4.19.58-v7l+ 的 Raspberry Pi 4 上运行。