C starter question

W

Wolfgang Draxinger

Antoninus said:
You need to supply a FILE* to ferror().

Sorry, that were my mistakes, and I hereby take responsibility for them. I
didn't test that code yet, yes lazy and a little bit careless. Anyway, I
did that now, here's there working and checked code, complete with testing
entry point. Compile with

cc -DTEST -o calluname calluname.c

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>

#define BLOCK_LENGTH 100
char * get_operating_system() {
FILE *fil;
char *output = 0;
size_t output_length = 0;
size_t output_read = 0;

fil = popen("uname -snm", "r");
if( !fil ) {
perror("error calling uname: ");
return 0;
}

while( !feof(fil) ) {
if( output_read + BLOCK_LENGTH + 1 > output_length ) {
char * o_new =
realloc(output,
output_length += BLOCK_LENGTH);
if( !o_new ) {
perror("error allocating memory: ");
break;
}
output = o_new;
}
output_read += fread(output +
output_read,
BLOCK_LENGTH,
1,
fil);
if( ferror(fil) ) {
fprintf(stderr, "error reading from uname
stdout\n");
break;
}
}
if( output &&
output_length > 0 &&
output_read > 0 ) {
memset(output + output_read, 0,
output_length - output_read);
}

pclose(fil);

return output;
}

#ifdef TEST
int main(int argc, char *argv[])
{
char *OS = get_operating_system();
if( !OS )
return EXIT_FAILURE;
puts(OS);
free(OS);
return EXIT_SUCCESS;
}
#endif
 
W

Wolfgang Draxinger

rudra said:
Thanks for all your reply.
As for WD, fortran do provide a way to get output from stdout, but no
std. conforming way for call system info like nisdomain or uname!

How about doing syscalls? If fork, pipe, dup2 and exec are avaliable, you
can reimplement the functionality of popen with those.

Wolfgang
 
K

Keith Thompson

Wolfgang Draxinger said:
How about doing syscalls? If fork, pipe, dup2 and exec are avaliable, you
can reimplement the functionality of popen with those.

If the system provides fork, pipe, dup2, and exec, it will probably
provide popen as well.
 
K

Kaz Kylheku

If the system provides fork, pipe, dup2, and exec, it will probably
provide popen as well.

I see something about Fortran above there. It's conceivable that POSIX bindings
for Fortran might have fork, pipe, dup and exec, but omit popen. Why? Because
popen is tied to FILE *, which is very C specific. You want a function like
popen, but one that integrates with the way Fortran natively does I/O.

Of course, if we are talking about C POSIX bindings, you clearly don't have
a complete POSIX implementation if popen is missing.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top