我试图在创建文件并向其写入数据后获取文件的大小。我得到的值似乎与实际文件大小不符。这是我的程序。请告诉我如何以位、字节、千字节和兆字节显示文件大小。根据我的说法,文件大小应该是 288 位、36 字节、0.03515626 千字节和 0.000034332 兆字节。
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#define PERMS 0777
int main(int argc, char *argv[])
{
int createDescriptor;
int openDescriptor;
char fileName[15]="Filename1.txt";
umask(0000);
if ((openDescriptor = creat(fileName, PERMS )) == -1)
{
printf("Error creating %s", fileName);
exit(EXIT_FAILURE);
}
if(write(openDescriptor,"This will be output to testfile.txt\n",36 ) != 36)
{
write(2,"There was an error writing to testfile.txt\n",43);
return 1;
}
if((close(openDescriptor))==-1)
{
write(2, "Error closing file.\n", 19);
}
struct stat buf;
fstat(openDescriptor, &buf);
int size=buf.st_size;
printf("%d\n",size);
printf("%u\n",size);
return 0;
}