【发布时间】:2023-03-15 02:39:01
【问题描述】:
是否有任何方法/函数可以与 int file = open(filepath, flag); 一起使用,因为我正在尝试实现 flock 并且因为 ifstream file; file.open("filepath"); 无法与 flock() 一起使用?
我正在尝试学习如何在 C++ 中实现flock(),我在网上找到了一些示例。这是我写的:
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);
但是当我使用std::ifstream::open() 打开文件时,我不能使用flock(),因为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 也会在提交上述一个或多个值时打开,然后关闭。
接下来,我有一个 bash,它定期 wgets 来自 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 上运行。
【问题讨论】:
-
使用“常规”C 文件界面?
-
@molbdnilo 如果我知道该怎么做,或者我知道那是什么,我就不会在这里发布了,我会吗?我正在网上阅读我需要什么以及我可以使用什么!但我没有大局,也没有知识。我在旅途中学习。
-
以下是您可以使用
int file执行的操作:C-style file input/output -
@acraig5075:不,那是 C 风格的
FILE*。这是一个 POSIXint fd。
标签: c++