int main()
{
FILE *read_fp;
char buffer[BUFSIZ + 1];
int chars_read;
memset(buffer, '\0', sizeof(buffer));
read_fp = popen("cat popen*.c | wc -l", "r");
if (read_fp != NULL) {
chars_read = fread(buffer, sizeof(char), BUFSIZ, read_fp);
while (chars_read > 0) {
buffer[chars_read - 1] = '\0';
//buffer[chars_read] = '\0';
printf("Reading:-\n %s\n", buffer);
chars_read = fread(buffer, sizeof(char), BUFSIZ, read_fp);
}
pclose(read_fp);
exit(EXIT_SUCCESS);
}
exit(EXIT_FAILURE);
}
fread() returns the number of items
successfully read
I think the following line should be changed from
buffer[chars_read - 1] = '\0';
to
buffer[chars_read] = '\0';
Do I get it right?
Are you tring to NULL terminate the string read? If so, then yes,
buffer[chars_read] = '\0';would be the way to do that.Other than that, the structure of your loop could be easier understood if you did it as
or more traditional