Visit Our UNIX and Linux User Community


Hello


 
Thread Tools Search this Thread
Top Forums Programming Hello
# 1  
Old 08-15-2009
Hello

Hello
Could u tell me how to read an integer froma file?
i have already written a C code to write an integer to a file,
but i'm doubt how to write code to read an integer
# 2  
Old 08-15-2009
read C Programming Language chapter 7 : INPUT AND OUTPUT
# 3  
Old 08-15-2009
Please use more descriptive titles for your posts. "Hello" won't tell anyone what's it about.

As for your question, how did you write the integer to a file? For fprintf() there's fscanf, for write() there's read(). And just as you opened the file with "w" or "w+", you can use "r" or "r+".
# 4  
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;
}

Previous Thread | Next Thread
Test Your Knowledge in Computers #805
Difficulty: Medium
The goal of a Digital Signal Processor (DSP) is usually to measure, filter or compress discrete digital signals.
True or False?

Featured Tech Videos