I tried this int file_desc,bytes,a=1112,val; char *conv_buf,*char_buf; conv_buf=(char*) malloc (10); char_buf=(char*) malloc (10); sprintf(conv_buf,"%d ",a);//converted file_desc=open("text.txt",O_RDWR); write(file_desc,conv_buf,10); //taking pointer to the very start lseek(file_desc,0,SEEK_SET); //retrieval bytes=read(file_desc,char_buf,10); val=atoi(char_buf); val=val+1; printf("%d",val);
At first i used sprintf( ) function which instead of printing to the stdout saves the string to the conv_buf and i wrote it to the file.
In the end i read the file again and used atoi( ) . Atoi is used where we have to convert the charachter string to the integer . Note: atoi( ) works for the ASCII decimal range of 48 (' 0 ') to 57 (' 9 ') and it will exit immediately as soon as it encounters any printable character out of this range.
To write a integer value in a file , you can simply typecast your buffer characters into the int and writing these integers into the file. moreover when you wish to get back your original characters , you should simply typecast to char and string these characters into buffer.
second you can use putc() function , putc function converts the appropriate character to unsigned integer and by storing this integer you can write these integers into the file , now if you want to read your original characters then you can use getc () function , the functionality of getc is vice versa of putc .. after printing the putc buffer you can see your original characters.