我在做:
FILE *in;
extern FILE *popen();
char buff[512];
if (!(in = popen("df / | tail -n +2 | awk '{ print $1 }'", "r"))) {
exit(1);
}
while (fgets(buff, sizeof(buff), in) != NULL ) {
printf("Output: %s", buff);
}
所以,一旦我buff
,我如何将s0
附加的字符添加到最后,以便我可以将此char
传递给函数以使用它?
答案 0 :(得分:0)
如果您的缓冲区足够大,您可以使用strcat()
将字符追加到字符串中。如果不是,你必须分配更多的内存。
答案 1 :(得分:0)
您无法向buff
添加任何内容,因为您会写入不属于您的内存。您必须在堆上分配内存并将buff
复制到该内存。确保分配足够的内存,以便实际附加内容。
请注意,如果fgets
调用未使用整个512个字符,您可以调用use strlen(buff)
来检查读取的字符数,然后再写入buff + strlen(buff)
答案 2 :(得分:0)
这样的事情可以解决问题:
char buff[512];
size_t pos = 0;
...
while (fgets(buff + pos, sizeof(buff) - pos, in) != NULL) {
printf("Output: %s\n", buff + pos);
pos += strlen(buff + pos);
}
如果您想要添加不是来自文件的字符,您可以扩展这个想法:
strcpy(buff + pos, "s0");
pos += strlen(buff + pos);
或
buf[pos++] = 's';
buf[pos++] = '0';
buf[pos++] = '\0';
您必须确保缓冲区不会溢出。
答案 3 :(得分:0)
对于非常c ++的方式:
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <string>
#include <sstream>
int main() {
FILE *in;
char buff[512];
if (!(in = popen("df /", "r"))) {
return 1;
}
fgets(buff, sizeof(buff), in); //discard first line
while (fgets(buff, sizeof(buff), in) != NULL ) {
std::istringstream line(buff);
std::string s;
line >> s; // extract first word
s += "s0"; // append something
std::cout << s << '\n';
}
return 0;
}
原始标题指定了c ++。对于编辑字符串,我建议使用C ++而不是C,除非你想要过度优化。