Sponsored Content
Full Discussion: Hello
Top Forums Programming Hello Post 302344358 by dr_mabuse on Sunday 16th of August 2009 05:14:13 AM
Old 08-16-2009
details are as follows: i write succes. but reading always returns 11.



//Write a program which creates a file which writes and reads an integer
//from that file.


#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>


#define BUFF_SIZE 1024

int main(int argc, char *argv[]){

int fd, fd2;

if(argc != 3){

printf("Input Format: \'./a.out\' \'int\' \'file\'\n");
exit(1);
}

printf("Integer: %d\t", atoi(argv[1]));
printf("File Name: %s\n", argv[2]);

if((fd = open("file", O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR)) < 0){

perror("Exit\n");
exit(1);
}

//char tmp[12] = {0x0};
char tmp[4];
sprintf(tmp, "%d\n", atoi(argv[1]));

write(fd, tmp, sizeof(tmp));

printf("========Writing COMPLETED SUCCESSFULLY========\n\n");
close(fd);
//======================================

if((fd2 = open("file", O_RDONLY, S_IRUSR | S_IWUSR)) < 0){
perror("Opening file for read failed...\n");
exit(1);
}

int number;
char *buff[BUFF_SIZE];
char str[10];

if(read(fd, buff, sizeof(tmp)) < 0){
perror("Reading failed...\n");
exit(1);
}
number = sprintf(str, "%d", buff);
printf("%d\n", number);

printf("READING COMPLETED SUCCESSFULLY\n");
close(fd2);

return 0;
}
 
All times are GMT -4. The time now is 04:21 AM.
Unix & Linux Forums Content Copyright 1993-2022. All Rights Reserved.
Privacy Policy