Hi all,
Is there a good way to create a new file with 1024 bytes, and initiate it to all 0's ?
Thank you...
Printable View
Hi all,
Is there a good way to create a new file with 1024 bytes, and initiate it to all 0's ?
Thank you...
Hmm I'm assuming you want the file of size 1024 bytes with all zeros in it, so you may be looking at:
I must admit looks pretty horrible and I'm pretty sure someone has a neater solution :)Code:#include <stdio.h>
#define SIZE 1024
int main(int argc, char **argv)
{
FILE *fp = fopen("sample.txt","w");
int i = 0, c = 0;
if (fp == NULL) {
fprintf(stderr,"Could not open for writing!\n");
exit(1);
}
for (i = 0; i < SIZE; i++)
{
c = fputc("0",fp);
if (c == EOF)
fprintf(stderr,"Error!\n");
}
if(fclose(fp) != 0)
{
fprintf(stderr,"Could not close properly!\n");
exit(1);
}
return 0;
}
If you mean 0 as in character '0'...
Or 0 as in binary 0...Code:char bytes[1024];
for( int i=0; i<1024; ++i )
bytes[i] = '0';
fwrite( bytes, 1, 1024, f );
Code:char bytes[1024] = {0};
fwrite( bytes, 1, 1024, f );
Code:#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
int main(void)
{
char *filename = "slappy.dat";
char fill[1024];
int fd;
memset(fill, '0', sizeof(fill));
if((fd = open(filename, O_WRONLY | O_TRUNC | O_CREAT,
S_IRUSR | S_IWUSR)) == -1)
{
puts("Error opening file for writing!");
exit(1);
}
if(write(fd, fill, sizeof(fill)) != sizeof(fill))
puts("Error writing to file!");
close(fd);
return 0;
}
EDIT: Don't ask me why it looks like the 0's are in 2 columns...the forum is doing that for some reason. The 0's are actually all adjacent to each other in my output file.Quote:
itsme@itsme:~/C$ cat slappy.dat
00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 000000000000000000000000itsme@itsme:~/C$
Indeed it does. You see, fputc doesn't take a string as an argument. ;)Quote:
Originally Posted by 0rion
Quzah.