1

I'd like to apologize for my poor english, for it is not my native language

So, here's my question. Is there any way, in C language, to read from my stdout, and to turn whatever I read into a *char ? I can only use functions read, write, malloc and free.

My actual code looks like this

char* acquire_shape()
{
    char *buffer[BUF_SIZE + 1];
    int ret;

    ret = read(0, buffer, BUF_SIZE)
    buffer[ret] = '\0';
    return *buffer;
}

but I can't get it into a character string.

Haris
  • 12,120
  • 6
  • 43
  • 70
  • That's not a character string; Its a pointer array. Normally you would use `char buffer[BUF_SIZE+1];` though it looks like you need a dynamic allocation since you're returning this from *somewhere*. And hard-coding your descriptors? Bad idea. – WhozCraig Sep 01 '13 at 20:16
  • I didn't get that part on hard-coding descriptors. What do you mean? – zubergu Sep 01 '13 at 20:34

3 Answers3

0

Note, you need to release the memory allocated with malloc at some point using free:

char* acquire_shape(int fd) {
    char *buffer = malloc(BUF_SIZE + 1);
    int ret;

    if (buffer == NULL)
      return NULL;

    ret = read(fd, buffer, BUF_SIZE);
    buffer[ret] = '\0';
    return buffer;
}
jev
  • 2,023
  • 1
  • 17
  • 26
0

char buffer[BUF_SIZE + 1]; is what you almost mean... except you cannot return it correctly since it's a pointer to local storage (which is undefined after the function returns). Your best bet is to change your function to something like this:

char* acquire_shape(char *buffer)
{
    int ret;

    ret = read(0, buffer, BUF_SIZE)
    buffer[ret] = '\0';
    return *buffer;
}

and call it like this:

    char mybuffer[BUF_SIZE + 1];
    acquire_shape(mybyffer);
mah
  • 39,056
  • 9
  • 76
  • 93
0

The declaration of char *buffer[BUF_SIZE + 1]; is not a pointer to type char, but rather a pointer to a pointer of type char. If you want to create a pointer to char you will need to allocate memory for your buffer:

char *buf = (char *) malloc(BUFSIZE + 1);

if (buf == NULL)
    return NULL;

You can then use the variable buf exactly how you used your buffer variable in your code sample.

sardoj
  • 33
  • 1
  • 4