Link to home
Start Free TrialLog in
Avatar of achille67
achille67

asked on

file reading and writing

how can i use a simple while loop to read from a buffer to a  file &&
from a file to a file in C
Avatar of manish_regmi
manish_regmi

hi,
 If you opened the file using open, you can use read() and write().
ssize_t read(int fd, void *buf, size_t count);

ssize_t write(int fd, const void *buf, size_t count);
write to a file.

regards manish
Avatar of achille67

ASKER

thanks, i know i should use
ssize_t read(int fd, void *buf, size_t count);

ssize_t write(int fd, const void *buf, size_t count);
but i was sure how i should call them inside another function
thanks, i know i should use
ssize_t read(int fd, void *buf, size_t count);

ssize_t write(int fd, const void *buf, size_t count);
but i wasn't sure how i should call them inside another function
hi,
 read() function reads the data from file to memory.
fd is the descriptor of the file you get by open.
buf is the buffer used to store the data.
count is the no of bytes to read.

eg

char buf[512];
int fd;
fd=open("/xtz", O_RDWR);
read(fd, &buf, 512);


this will copy 512 bytes of data from the file /xtz to buf.

similarly.

write(fd, &buf, 512) will write the data stored in buf to the file.

regards manish


hi,
 read() function reads the data from file to memory.
fd is the descriptor of the file you get by open.
buf is the buffer used to store the data.
count is the no of bytes to read.

eg

char buf[512];
int fd;
fd=open("/xtz", O_RDWR);
read(fd, &buf, 512);


this will copy 512 bytes of data from the file /xtz to buf.

similarly.

write(fd, &buf, 512) will write the data stored in buf to the file.

regards manish


Hi achille67,
> but i was sure how i should call them inside another function
declare the file descriptor in as global or pass it as argument to a function, like:

void write_single_block(int fd){
    write(fd,your_buffer,your_len);
    [...]
}

Cheers,
Stefan
ASKER CERTIFIED SOLUTION
Avatar of da99rmd
da99rmd

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks Rob, you can read people's mind. That is the dam loop!!!