3
votes
/* Write and rewrite */
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>

int main(int argc,char* argv[]){
 int i = 0;
 int w_rw = 0;
 int fd = -1;
 int bw = -1;
 int nob = 0;
 char* file_name = "myfile";
 char buff[30] = "Dummy File Testing";

 w_rw = 1;       // 1 - write , 2 - rewrite
 nob = 1000000;  // No of bytes to write

 printf("\n File - Create,Open,Write \n");

 for(i = 0; i < w_rw; i++){
        printf("fd:%d line : %d\n",fd,__LINE__);
        if((fd = open(file_name,O_CREAT | O_RDWR))< 0){
                perror("Open failed!");
                return -1;
        }

        printf("fd:%d",fd);
        if((bw = write(fd,buff,nob)) < 0){
                perror("Write failed!");
                return -1;
        }
        printf("\n Bytes written : %d \n",bw);
 }

 return 0;
}

I'm getting a write error, Bad address failure when tried to write 1MB bytes of data. why is that so ?

3

3 Answers

2
votes

According to man of write write() writes up to count bytes from the buffer pointed buf to the file referred to by the file descriptor fd so you are overrunning the string buffer.

If you want to just fill the file with that string try fwrite, you can specify the string length and the total number of times to write the buffer (nob/strlen(buff) ?).

2
votes
 ssize_t write(int fd, const void *buf, size_t nbytes);

write() system call will read nbytes bytes from buf and write to file referred by the file descriptor fd.

In your program buf is small compare to nbytes so write() trying to access invalid address location, so its giving Bad Address error.

Your buf is buff[30] change to buf[1000000] you can solve your problem.

Bad Address error means that the address location that you have given is invalid.

Wikipedia giving good explanation with example program about write.

1
votes

Your buff array should be at least nob bytes long for the write call to succeed...