将文件复制到C中的字符串
Copy file into string in C
我正在尝试将内存信息读入 c 中的字符串,但遇到了一些麻烦。这是我目前拥有的。
FILE * fpipe;
long length;
char * command = "free";
fpipe = (FILE*) popen(command, "r")));
fseek(fpipe, 0, SEEK_END);
length = ftell(fpipe);
fseek(fpipe, 0, SEEK_SET);
bufer = (char*) malloc(length);
char line[128];
if(fpipe)
{
while(fgets(line, sizeof line, fpipe))
{
strcat(buffer, line);
}
}
我可以打印行,但不能将其添加到缓冲区。在此先感谢您的帮助。
您正在从文件中读取二进制数据。因此,您不能将其视为空终止字符串。
使用 memcpy()
而不是 strcat。
对我之前的评论稍作修改,现在我们可以看到你的代码的问题:如果你有一个管道,你只能寻求向前,而不是向后.一旦你搜索到最后,你就再也回不去了,所有的数据都丢失了。
相反,您需要在每次迭代时动态分配 reallocate 缓冲区。
这是一个工作示例:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char *command="ls -ltr";
FILE* fp;
char line[128];
char* buffer=NULL; // Buffer to store the string
unsigned int size=0;
fp=popen(command,"r");
while (fgets(line,sizeof(line),fp))
{
size+=strlen(line);
strcat(buffer=realloc(buffer,size),line);
}
printf("Contents received from pipe\n ");
fputs(buffer,stdout);
free(buffer);
fclose(fp);
return 0;
}
我正在尝试将内存信息读入 c 中的字符串,但遇到了一些麻烦。这是我目前拥有的。
FILE * fpipe;
long length;
char * command = "free";
fpipe = (FILE*) popen(command, "r")));
fseek(fpipe, 0, SEEK_END);
length = ftell(fpipe);
fseek(fpipe, 0, SEEK_SET);
bufer = (char*) malloc(length);
char line[128];
if(fpipe)
{
while(fgets(line, sizeof line, fpipe))
{
strcat(buffer, line);
}
}
我可以打印行,但不能将其添加到缓冲区。在此先感谢您的帮助。
您正在从文件中读取二进制数据。因此,您不能将其视为空终止字符串。
使用 memcpy()
而不是 strcat。
对我之前的评论稍作修改,现在我们可以看到你的代码的问题:如果你有一个管道,你只能寻求向前,而不是向后.一旦你搜索到最后,你就再也回不去了,所有的数据都丢失了。
相反,您需要在每次迭代时动态分配 reallocate 缓冲区。
这是一个工作示例:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char *command="ls -ltr";
FILE* fp;
char line[128];
char* buffer=NULL; // Buffer to store the string
unsigned int size=0;
fp=popen(command,"r");
while (fgets(line,sizeof(line),fp))
{
size+=strlen(line);
strcat(buffer=realloc(buffer,size),line);
}
printf("Contents received from pipe\n ");
fputs(buffer,stdout);
free(buffer);
fclose(fp);
return 0;
}