将char指针写入文件,读取文件并检查大小?

时间:2019-03-27 05:11:42

标签: c file-io malloc

我试图读取指向文件的char指针,然后检查该文件的大小。如果我正确执行此文件,则应为256个字节。我想创建一个具有char *数组fwrite的文件,然后检查该文件以查看其大小并打印出以字节为单位的大小。我的代码在下面。

此外,我应该在窥视中输入字符,而不是字符,但是我不确定如何做到这一点。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
    double price;
    char title[60];
} game;
void main(){

    FILE* fp = fopen("file.txt","w+"); //file.txt will be blockchain text file.

    char* peep = malloc(256);

    for(int i = 0; i<256;i++){      // Populate array with 256 2's.
        peep[i] = 2;                //THIS SHOULD BE CHARACTERS, ONE CHARACTER PER INDEX
    }
    for (int i = 0; i < 256 ;i++){   //Print array to verify if has 256 2 char.                             
        printf("%d %d\n",peep[i],i);
    }
    int j = sizeof(peep)/sizeof(peep[0]); //amount of elements in array.

    fwrite(peep,sizeof(peep[0]),sizeof(peep)/sizeof(peep[0]),fp); //Writes 256 chars to the array, all of the peep.
    long fsize = 0; //Size of the file after writing
    if (fp != NULL){
        fseek(fp,0,SEEK_END);
        fsize = ftell(fp); 
    }
    if (fsize != 256){
        printf("\nPEEP NOT FULL,size is %ld",fsize);
    }
   // fseek(fp,0,SEEK_SET); //Go back to start of file, since we were at the end.
}

1 个答案:

答案 0 :(得分:2)

sizeof(peep)/sizeof(peep[0])等效于sizeof(char*)/sizeof(char) = 8字节(64位)

所以您应该更改

fwrite(peep,sizeof(peep[0]),sizeof(peep)/sizeof(peep[0]),fp);

fwrite(peep,sizeof(peep[0]),256,fp);