Reputation: 1845
I tried using the following code to read a text from the keyboard and write it into the file text.dat. The file was created but it was empty.
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <io.h>
#include <string.h>
int main()
{
char s[201];
int n,f = open("text.dat", O_RDWR | O_CREAT);
while (fgets(s,200,stdin) != NULL)
write(f, s,sizeof(s));
close(f);
return 0;
}
Upvotes: 0
Views: 1571
Reputation: 1
You are opening file in wrong way. Try open("text.dat", O_RDWR | O_CREAT,0666 );
P.S.
You simply don't have write access to file.
Upvotes: 0
Reputation: 25053
The write
is wrong. Try this:
write(f, s, sizeof(s));
The second parameter should be a pointer to the beginning of s
. What you're actually passing is a pointer to the pointer.
While you're at it, get rid of that unused int n
:
int f = open("text.dat", O_RDWR | O_CREAT);
Edited to add
Your write()
must use strlen()
instead of sizeof()
- you're probably writing out uninitialized junk, which makes it appear that the file is empty.
write(f, s, strlen(s));
Upvotes: 0
Reputation: 17848
write(f, s, strlen(s))
Though I'd use read()
instead of fgets()
and used its result instead of strlen()
Upvotes: 1