1

I am reading an input file in the parent and based on the content in the file, I pass them to one of the two child processes.

    char a[20],b[20],c[20];

    pFile = fopen ("instruction.dat","r");
while(!feof(pFile))
{
fscanf(pFile,"%s %s %s",a,b,c);
switch(a[0])
    {
    case 'f': write(fds1[1],b,sizeof(b));
           write(fds1[1],c,sizeof(c));
           write(1,"\nAFRCF",6);
           break;

    case 'a': write(fds2[1],b,sizeof(b));
           write(fds2[1],c,sizeof(c));
           write(1,"\nAFRCA",6);
           break;

    default: write(1,err,sizeof(err));
          //printf("\n Instruction.dat read error");
    }
}

Now, the problem I am facing is that the sizeof(a) operator returns the size of the allocated memory to the array and thus the child process receives some garbage along with the actual contents from the input file. I can't predict the size of the array beforehand so I can't use dynamic allocation (malloc or realloc) to give the exact size of the array.

What is the way to pass the exact size of strings (after reading the input file) to the write() ?

1
  • Passing exact string length to write (among a million others) seems a more suitable title for the question, just saying :) Commented Jan 22, 2014 at 15:41

2 Answers 2

3

Use the strlen function to get the size of the strings not sizeof

write(fds1[1],b,strlen(b));
Sign up to request clarification or add additional context in comments.

1 Comment

Hell you were fast! By the way, love your VsVim extension. Thanks for that :)
2

I think you're looking for strlen string function. For example:

write(fds1[1],b,strlen(b));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.