- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我有一个 C++ 可执行文件,在正常使用中,它以下列方式接受文件名作为参数选项:
executable -i myFile.txt
我想使用 Bash 进程替换来创建一个“虚拟文件”并按以下方式将信息(简单的逐行数据)发送到此可执行文件:
executable -i <(echo "${myData}")
但是,当我使用这个进程替换时,我的 C++ 程序没有访问信息。 C++程序中主要文件读取部分代码如下:
ifstream file1 (fileName1);
string line;
int currentLineNumber = 0;
if (verboseFlag == 1) {cout << "reading data from file " << fileName1 << "..." << endl;}
while (getline (file1, line)){
currentLineNumber++;
if (verboseFlag == 1) {cout << "line " << currentLineNumber << ": ";}
istringstream linestream(line);
string item;
int itemNumber = 0;
while (getline (linestream, item, ',')){
itemNumber++;
if (verboseFlag == 1) {cout << "item " << itemNumber << ": " << item << " ";}
// data
if (itemNumber == 1) {x[currentLineNumber]=atof(item.c_str());}
if (itemNumber == 2) {y[currentLineNumber]=atof(item.c_str());}
}
}
file1.close();
你能为我指出解决这个阅读问题的正确方向吗?是否有一些更好的方法既适用于正常文件读取,也适用于进程替换"file"读取?
我是这个流程替代的新手,非常感谢任何帮助。
编辑:
根据一些评论,下面是一个说明我遇到的问题的最小工作示例:
// definition of standard input/output stream objects
#include <iostream>
// manipulate strings as though they were input/output streams
#include <sstream>
// input and output operations
#include <stdio.h>
// file input and output operations
#include <fstream>
// manipulate C strings and arrays
#include <string.h>
// classify and transform individual characters
#include <ctype.h>
// Standard General Utilities Library
#include <stdlib.h>
// getopts (handle command line options and arguments)
#include <unistd.h>
// sstream (handle conversion from char* to double)
#include <sstream>
using namespace std;
double returnDoubleFromPointerToChar(const char *cText){
std::stringstream ss ( cText );
double dText = 0;
ss >> dText;
return dText;
}
int returnNumberOfLinesInFile(const char *fileName1){
int lineCount = 0;
string line;
ifstream file1(fileName1);
while (std::getline(file1, line))
++lineCount;
file1.close();
return lineCount;
}
int main (int argc, char **argv){
char *fileName1 = NULL; // input file name (i) (required input)
int verboseFlag = 0; // verbose flag (v)
int index; // internal variable
int c; // internal variable
opterr = 0;
// process command line arguments and options
while ((c = getopt (argc, argv, "i:v")) != -1)
switch (c){
case 'i':
fileName1 = optarg;
break;
case 'v':
verboseFlag = 1;
break;
case '?':
if (
optopt == 'i'
){
fprintf (stderr, "option -%c requires an argument.\n", optopt);
}
else if (isprint (optopt)){
fprintf (stderr, "unknown option `-%c'.\n", optopt);
}
else {
fprintf (stderr, "unknown option character `\\x%x'.\n", optopt);
}
return 1;
default:
abort ();
}
for (index = optind; index < argc; index++) printf ("non option argument %s\n", argv[index]);
if (verboseFlag == 1){
cout << endl;
cout << "input file name: " << fileName1 << endl;
}
// Determine the number of lines in the input file.
int numberOfLinesInInputFile=returnNumberOfLinesInFile(fileName1);
if (verboseFlag == 1) {cout << "number of lines in input file: " << numberOfLinesInInputFile << endl;}
// number of data points
int n=numberOfLinesInInputFile-1;
// x variable
double x[n];
// y variable
double y[n];
// Access the data in the input file.
ifstream file1 (fileName1);
string line;
int currentLineNumber = 0;
if (verboseFlag == 1) {cout << "reading data from file " << fileName1 << "..." << endl;}
while (getline (file1, line)){
currentLineNumber++;
if (verboseFlag == 1) {cout << "line " << currentLineNumber << ": ";}
istringstream linestream(line);
string item;
int itemNumber = 0;
while (getline (linestream, item, ',')){
itemNumber++;
if (verboseFlag == 1) {cout << "item " << itemNumber << ": " << item << " ";}
// data
if (itemNumber == 1) {x[currentLineNumber]=atof(item.c_str());}
if (itemNumber == 2) {y[currentLineNumber]=atof(item.c_str());}
}
if (verboseFlag == 1) {cout << endl;}
}
file1.close();
return 0;
}
编辑:
我在下面添加了解决方案代码(根据其他人的评论):
// include WBM C++ library
// #include "lib_cpp.c"
// definition of standard input/output stream objects
#include <iostream>
// manipulate strings as though they were input/output streams
#include <sstream>
// input and output operations
#include <stdio.h>
// file input and output operations
#include <fstream>
// manipulate C strings and arrays
#include <string.h>
// classify and transform individual characters
#include <ctype.h>
// Standard General Utilities Library
#include <stdlib.h>
// getopts (handle command line options and arguments)
#include <unistd.h>
// sstream (handle conversion from char* to double)
#include <sstream>
using namespace std;
// example usage:
// ./graph2d -i data.txt -o data.eps -v
// ./graph2d -i data.txt -o graph.eps -t "training test error versus epochs" -x "epochs" -y "error measure" -v
// ./graph2d -i data.txt -o graph.eps -t "training test error versus epochs" -x "epochs" -y "error measure" -a 70 -b 50 -c 22 -d 7 -v
// ./graph2d -i <(echo "${dataForTrainingErrorVersusEpoch}") -o graph.eps -t "training test error versus epochs" -x "epochs" -y "error measure" -v
double returnDoubleFromPointerToChar(const char *cText){
std::stringstream ss ( cText );
double dText = 0;
ss >> dText;
return dText;
}
int main (int argc, char **argv){
char *fileName1 = NULL; // input file name (i) (required input)
char *fileName2 = NULL; // output file name (o) (required input)
char *graphTitleMain = NULL; // graph title (t)
char *graphTitleAxisx = NULL; // graph x axis title (x)
char *graphTitleAxisy = NULL; // graph y axis title (y)
double axisyMaximum = DBL_MAX; // y axis maximum (a)
double axisyMinimum = DBL_MAX; // y axis minimum (b)
double axisxMaximum = DBL_MAX; // x axis maximum (c)
double axisxMinimum = DBL_MAX; // x axis minimum (d)
int verboseFlag = 0; // verbose flag (v)
int index; // internal variable
int c; // internal variable
opterr = 0;
// process command line arguments and options
while ((c = getopt (argc, argv, "i:o:t:x:y:a:b:c:d:v")) != -1)
switch (c){
case 'i':
fileName1 = optarg;
break;
case 'o':
fileName2 = optarg;
break;
case 't':
graphTitleMain = optarg;
break;
case 'x':
graphTitleAxisx = optarg;
break;
case 'y':
graphTitleAxisy = optarg;
break;
case 'a':
axisyMaximum = returnDoubleFromPointerToChar(optarg);
break;
case 'b':
axisyMinimum = returnDoubleFromPointerToChar(optarg);
break;
case 'c':
axisxMaximum = returnDoubleFromPointerToChar(optarg);
break;
case 'd':
axisxMinimum = returnDoubleFromPointerToChar(optarg);
break;
case 'v':
verboseFlag = 1;
break;
case '?':
if (
optopt == 'i' ||
optopt == 'o' ||
optopt == 't' ||
optopt == 'x' ||
optopt == 'y' ||
optopt == 'a' ||
optopt == 'b' ||
optopt == 'c' ||
optopt == 'd'
){
fprintf (stderr, "option -%c requires an argument.\n", optopt);
}
else if (isprint (optopt)){
fprintf (stderr, "unknown option `-%c'.\n", optopt);
}
else {
fprintf (stderr, "unknown option character `\\x%x'.\n", optopt);
}
return 1;
default:
abort ();
}
for (index = optind; index < argc; index++) printf ("non option argument %s\n", argv[index]);
if (verboseFlag == 1){
cout << endl;
cout << "input file name: " << fileName1 << endl;
cout << "output file name: " << fileName2 << endl;
}
// x variable
vector<int> x;
// y variable
vector<int> y;
// Access the data in the input file.
ifstream file1 (fileName1);
string line;
int currentLineNumber = 0;
if (verboseFlag == 1) {cout << "reading data from file " << fileName1 << "..." << endl;}
while (getline (file1, line)){
currentLineNumber++;
if (verboseFlag == 1) {cout << "line " << currentLineNumber << ": ";}
istringstream linestream(line);
string item;
int itemNumber = 0;
while (getline (linestream, item, ',')){
itemNumber++;
if (verboseFlag == 1) {cout << "item " << itemNumber << ": " << item << " ";}
// data
if (itemNumber == 1) {x.push_back(atof(item.c_str()));}
if (itemNumber == 2) {y.push_back(atof(item.c_str()));}
}
if (verboseFlag == 1) {cout << endl;}
}
file1.close();
int numberOfLinesInInputFile = currentLineNumber + 1;
// number of data points
int n=numberOfLinesInInputFile;
// graph
if (verboseFlag == 1){
cout << "graph main title: " << graphTitleMain << endl;
cout << "graph x axis title: " << graphTitleAxisx << endl;
cout << "graph y axis title: " << graphTitleAxisy << endl;
}
// Create a new canvas.
TCanvas *c1 = new TCanvas(graphTitleMain, graphTitleMain); // #u
// Create a new graph.
//TGraph *graph = new TGraph(n, x, y);
TGraph *graph = new TGraph(n, &x[0], &y[0]);
// Set the graph titles.
graph->SetTitle(graphTitleMain);
graph->GetXaxis()->SetTitle(graphTitleAxisx);
graph->GetYaxis()->SetTitle(graphTitleAxisy);
// Set the marker styles.
graph->SetMarkerColor(2); // red
graph->SetMarkerStyle(kFullCircle); // circle
graph->SetMarkerSize(1); // default size
// Set the graph range, if ranges have been specified in command line options.
if (
axisyMaximum != DBL_MAX &&
axisyMinimum != DBL_MAX
){
if (verboseFlag == 1){
cout << "graph y axis minimum: " << axisyMinimum << endl;
cout << "graph y axis maximum: " << axisyMaximum << endl;
}
graph->GetYaxis()->SetRangeUser(axisyMinimum, axisyMaximum);
}
if (
axisxMaximum != DBL_MAX &&
axisxMinimum != DBL_MAX
){
if (verboseFlag == 1){
cout << "graph x axis minimum: " << axisxMinimum << endl;
cout << "graph x axis maximum: " << axisxMaximum << endl;
}
graph->GetXaxis()->SetRangeUser(axisxMinimum, axisxMaximum);
}
// Draw the canvas, then draw the graph and then save the canvas to an image file.
c1->Draw();
graph->Draw("ALP");
// disable ROOT messages
gErrorIgnoreLevel = 5000;
if (verboseFlag == 1) {cout << "saving file " << fileName2 << "..." << endl;}
c1->SaveAs(fileName2);
if (verboseFlag == 1) {cout << endl;}
return 0;
}
最佳答案
首先,我删减了你程序的三分之二,它仍然显示出问题。这明显更接近于最小值:
#include <iostream>
#include <fstream>
using namespace std;
int returnNumberOfLinesInFile(const char *fileName1){
int lineCount = 0;
string line;
ifstream file1(fileName1);
while (std::getline(file1, line))
++lineCount;
file1.close();
return lineCount;
}
int main (int argc, char **argv){
char *fileName1 = argv[1];
cout << "input file name: " << fileName1 << endl;
int numberOfLinesInInputFile=returnNumberOfLinesInFile(fileName1);
cout << "number of lines in input file: " << numberOfLinesInInputFile << endl;
ifstream file1(fileName1);
string line;
cout << "File contents: " << endl;
while (getline (file1, line)){
cout << "line: " << line << endl;
}
file1.close();
return 0;
}
这里的问题是您打开文件两次。 <(process substitution)
只运行一次命令并流式传输结果。如果您想再次读取输出,Bash 不会擅自再次运行该命令,因为该命令除了吐出文本之外还可以做很多其他事情。
确保您的程序只打开并读取一次内容,它就可以运行。这可能需要您稍微重写您的逻辑,或者只是懒惰并立即将其全部读入内存。
关于c++ - 在 C++ 中访问由 Bash 进程替换创建的 'virtual file',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14863142/
进程虚拟机和系统虚拟机有什么区别? 我的猜测是,进程 VM 没有为该操作系统的整个应用程序提供一种操作系统,而是为某些特定应用程序提供环境。 系统虚拟机为操作系统提供了一个安装环境,就像 Virtua
我在成员函数的上下文中理解 virtual,例如 virtual void frob()。但它在类声明的上下文中意味着什么,例如 class Foo : public virtual Bar? 对于给
根据 react-virtualized 文档,“AutoSizer 组件装饰 React 元素并自动管理宽度和高度属性,以便装饰元素填充可用空间”。 建议通常是加上height: 100%;或 fl
根据 this类似 StackOverflow 问题和其他文章,默认情况下 C# 方法是“非虚拟的”,我认为这意味着您不能在派生类中覆盖它们。 如果那是真的,能否请您向我解释一下,在下面的示例中,我如
我有一个基类Media和几个派生类,即DVD、Book等...基类写成: class Media{ private: int id; string title;
我搜索了一些关于虚函数声明的帖子,相信 =0 在 virtual void test()=0; 是固定句法所以 virtual void test()=NULL; virtual void test(
我正在使用 RV 列表加载具有自定义格式的大型文档。它非常有效,但我遇到了以下两个问题: 我目前在 cellmeasurer 中设置了一个列表 based on this计算行的动态高度(宽度是固定的
我一直在努力制作 this react virtualized table example工作 & 开始严重怀疑我的理智。我创建了一个 react 应用程序,我只是想在 App.js 中使用以下内容呈
我在Windows 7 Pro计算机上安装了Windows Virtual PC和Windows XP Mode。运行XP模式会在Virtual PC上自动安装XP。我想创建第二台与第一台相同的虚拟P
我使用 Virtual PC 来创建新的环境来测试我的安装程序。但我一定是做错了什么,因为内部装有 Vista 或 XP 的 VPC 镜像占用了大约 15GB 的磁盘空间(包括安装在其中的 VS200
是否可以为 Ubuntu 虚拟机动态分配处理器和内存?例如。进程在主机系统上运行,导致处理器的使用率从 30%-70% 上下波动,这些进程还占用 8GB 内存中 3GB-7GB 之间的波动量,即 1G
我正在使用“react-virtualized”来创建一个表。在该表中,一些数据可能显示为 'Brian Vaughn1'。 .此表格单元格应具有 font-weight: bold并且只应呈现文本,
我正在使用“react-virtualized”来创建一个表。在该表中,一些数据可能显示为 'Brian Vaughn1'。 .此表格单元格应具有 font-weight: bold并且只应呈现文本,
我一直在努力理解一段这样的代码: class A { // some class definition } class B { public: virtual A *s
基于 http://en.wikipedia.org/wiki/Virtual_inheritance class Animal { ... }; // Two classes virtually i
我看到 C++ 中的某些函数被声明为 virtual const int getNumber(); 但是如果函数声明如下有什么区别呢? const virtual int getNumber(); 这
问题来自C++ faq。 http://www.parashift.com/c++-faq-lite/protected-virtuals.html 使用公共(public)重载虚拟的代码: clas
这个问题在这里已经有了答案: How is "=default" different from "{}" for default constructor and destructor? (3 个答案
virtual final 函数(final 在基类)是否有任何 vtable/virtual 成本? class B{ public: virtual void fFinal() final
我有一个只包含 exe 文件(没有源代码)的 hello 工具。 你好工具结构: bin helloBin.exe helloRoot.exe conanfile.py conanfile.py
我是一名优秀的程序员,十分优秀!