Use popen
:
void dostuff(const char* s) {
FILE* f = fopen(s, "r");
FILE* p = popen("myscript.sh", "w");
char buf[4096];
while (size_t n = fread(buf, 1, sizeof(buf), f))
if (fwrite(buf, 1, n, p) < n)
break;
pclose(p);
}
You'll need to add error checking to make this robust.
Note that I prefer a const char*
, since it is more flexible (works with things other than std::string
) and matches what's going on inside. If you really prefer std::string
, do it like so:
void dostuff(const std::string& s) {
FILE* f = fopen(s.c_str(), "r");
⋮
Also note that the 4096-byte buffer was chosen because it matches the page size on most systems. This isn't necessarily the most efficient approach, but it'll be fine for most purposes. I've found 32 KiB to be a sweet spot in my own unscientific tests on a laptop, so you might want to play around, but if you are serious about efficiency, you'll want to switch to asynchronous I/O, and start readn+1 immediately after initiating writen.