1

I'm currently trying to write an integer variable using write function in the file. This is my code:

int main(int argc, char** argv){
int fd, nbMult, i;
char buf[4];
if((fd = open("data", O_CREAT|O_RDWR, 0777))==-1){
    perror("ERROR\n");
    exit(EXIT_FAILURE); 
}

do{ 
    printf("Bla bla ");
    if( scanf("%d", &nbMult) !=1 ) while( (i = getchar()) != '\n' );
}while(nbMult<1);
sprintf(buf, "%d", nbMult);
if( write(fd, buf, sizeof(int)) == -1 ){
    perror("ERROR\n");
    exit(EXIT_FAILURE);
}

close(fd);
return 0; }

It creates the file, but when I try to open it, it shows me "cannot display ". When I remplace the name of the file by data.txt it works but it shows strange character in the file. I have tried also to convert the Integer variable to String using sprintf() and it's the same issue.

16
  • How do you "access" the file? Commented Feb 15, 2018 at 20:59
  • Do you understand the difference between binary and text files? Commented Feb 15, 2018 at 21:00
  • 1
    I try to open the file: how? Commented Feb 15, 2018 at 21:01
  • 3
    If you want the file to contain readable text instead of binary, then something like sprintf() or fprintf() is the way to go. Show us that code, and we'll show you where you went wrong. Commented Feb 15, 2018 at 21:02
  • 1
    by typing gedit data in the console Commented Feb 15, 2018 at 21:03

1 Answer 1

3

The file does get created - and has sizeof(int) bytes. Its contents are the bytes making up the integer nbMult in memory.

The thing is, those are not the characters used to print nbMult on a terminal. For example, suppose you've typed in 1234 for nbMult. What you've typed in are actually the characters '1', '2', '3', '4' - whose numeric values are 49, 50, 51, 52 respectively (here's a program which illustates that). But the bytes you'll get in memory for nbMult, on a typical machine, are 210, 4, 0, 0, since:

* 210 ==  1234       % 2^8
*   4 == (1234/2^ 8) % 2^8
*   0 == (1234/2^16) % 2^8
*   0 == (1234/2^24) % 2^8

those are the "strange characters" you're seeing in the file.

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

2 Comments

Thanks, I can see that now ^^ I appreciate your help
@AnasMK: If you found this answer helpful, you can accept it by pressing the "v" sign on the margin.

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.