write function
I am having a problem getting this write function to work. All the parameters seem to be correct, but I get the following error message :
write error: Bad file descriptor
can someone tell me what is wrong here.
#include<stdio.h>
#include<unistd.h>
#include<errno.h>
#include<stdlib.h>
#include<fcntl.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<string.h>
int main()
{
char buffer[80];
char data[80];
int fd;
long int BEGIN=0;
printf("Enter a name of the file to write to: ");
fgets(buffer,80,stdin);
buffer[strlen(buffer)-1]='\0';
if((fd=open(buffer,O_APPEND)) < 0){
perror("open error: ");
exit(1);
}
if((lseek(fd,BEGIN,SEEK_SET)) == BEGIN-1){
perror("lseek error ");
exit(2);
}
printf("Enter the data to insert into the file: ");
fgets(data,80,stdin);
data[strlen(data)-1]='\0';
if(write(fd,data,sizeof(data)) != sizeof(data)){
perror("write error ");
exit(3);
}
close(fd);
return 0;
}
|