I am trying to write into a file, but it is not working. I can open a file, but while writing in the file using write function, tt is writting in the stdout itself, and the content of the file I opened remain unchanged.
#include<stdio.h>
#include<sys/file.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<limits.h>
#include<fcntl.h>
#include<stdlib.h>
#include<sys/uio.h>
main() {
char fn[30];
int fd,i=0;
int actualbytes,bytesstored;
char buffer[100];
printf("\nEnter the filename with path");
scanf("%s",fn);
if(fd=open(fn,O_WRONLY|O_CREAT,S_IWUSR|S_IWUSR)<0)
{
perror("open");
exit(0);
}
else
{
write(stdout,"\n\nEnter the contents for the file\n");
write(stdout,"press CTRl+D at the end of the file\n\n");
fflush(stdout);
while((buffer[i]=getc(stdin))!=EOF) i++;
buffer[i]='\0';
bytesstored=sizeof(buffer);
if(actualbytes=write(fd,buffer,bytesstored)<0)
{
perror("write");
exit(0);
}
else
{
write(stdout,"\n\nfile is opened successfully");
write(stdout,"\nThe contents are written"); fflush(stdout);
}
if(close(fd)<0)
{
perror("close");
exit(0);
}
else
printf("\nfile is closed");
}
}
<
has higher precedence than =
.
if((fd=open(fn,O_WRONLY|O_CREAT,S_IWUSR|S_IWUSR))<0)
There are a lot of problems with this code. Make sure you enable warnings on your compiler, it should complain about quite a few things:
write()
is in unistd.h
. You're not including that, so your program cannot be correct.
Once you include that, you'll notice (with warnings enabled), that you're calling it incorrectly at least 5 times: stdout is not a file descriptor, it's a FILE*
.
Use the printf()
family of functions to print things on the console.
Second big problem is your if
statements that have assignments in them.
if (a = b < 0) { ... }
is equivalent to:
if (a = (b < 0)) { ... }
So it's not doing what you think it is. You need to use parenthesis:
if ((fd = open(...)) < 0) { ... }
Note: you're always writing the full buffer to the file. Not all of it has been initialized. That doesn't sound like what you're after. Try only writing the data that you've read (you have that stored in i
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With