1

I wrote the following code in order to write some random characters to a text file:

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>

int main()
{
    int input_f = open("./input.txt", O_CREAT | O_APPEND |  O_RDWR ,0666);
    int i;
    for(i=0;i<50;i++)
    {
        int r = rand()%252;
        printf("%d size of r: %d\n",i,sizeof(r));
        write(input_f,r,sizeof(r));
        printf("%d we just wrote %d which is %c\n",i,r,r);
    }

    close(input_f);
}

I looked for some solutions to do this

Maybe someone here knows how can I fix this?

3
  • Why not random and what do you mean "not formatted"? Commented Apr 6, 2017 at 11:59
  • 1
    What error do you get? I'm guessing none, because your code doesn't print any error messages. Try checking the return value of open and write and writing an error message if they fail. (man perror and man strerror) Commented Apr 6, 2017 at 12:00
  • Seeing the error he got when he called write would give it away as well. Commented Apr 6, 2017 at 12:01

5 Answers 5

2
write(input_f,r,sizeof(r));

should be

write(input_f, &r, sizeof(r));

The second parameter is the address of the buffer you want to send according to the man page.

Also you should check the return value of the function to be equal to sizeof r.

Sign up to request clarification or add additional context in comments.

Comments

1

write(input_f,r,sizeof(r)); should be write(input_f,&r,sizeof(r)); because write takes a pointer to the data to be written, not the data directly.

Other then that you should be checking the result of the open call, and write calls they can fail.

1 Comment

Beaten to it by mch.
1

You're calling write wrong.

If you'd included unistd.h, you would have gotten a prototype and the compiler would have corrected you.

write(input_f,&r,sizeof(r)); //the 2nd arg is a void const*

Also, size_t arguments to printf require "%zu", and you should be checking for errors.

1 Comment

Thanks you for the tips!
1

Others have already said why it doesn't work

I just want to add that you should also write :

#include <unistd.h>

Or else you'll get warnings during compilation.

1 Comment

Thanks you for the tips!
0

The write() function do not take an int as second parameter but a pointer (void *) on a buffer, and its length. It means you will have to convert your int into a string in a buffer first (with sprintf() for instance) and then output the buffer to the file (with write())

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.