Ftell在C中返回错误的二进制文件大小

时间:2018-12-14 10:25:30

标签: c binaryfiles

我想用ftell获取字节数以读取二进制文件中的数据,而ftell返回108个字节而不是144(我的二进制文件实际大小)
在这里,我创建二进制文件:

void database_add(char *moviestxt_filename, char *database_filename)
{
    FILE *txt = fopen(moviestxt_filename,"r");
    FILE *bin = fopen(database_filename,"wb");
    if(bin == NULL) { printf("Binary file open error\n"); return 0;}`    
    if(txt == NULL) {printf("txt file open error\n"); return 0;}
    movie m; int i=1;
    while(1)
{
        fscanf(txt,"%s",&m.title);
        fscanf(txt,"%d",&m.relese_year);
        fscanf(txt,"%f",&m.imdb_rate);
        fscanf(txt,"%d",&m.duration.hours);
        fscanf(txt,"%d",&m.duration.minutes);
        fseek(bin, 0 , SEEK_END);
        fwrite(&m, sizeof(m), 1, bin); 
        if(feof(txt)) break;
    }
}

这是我要读取二进制文件的功能:

movie* database_read(char *database_filename)
{
    FILE *bin = fopen(database_filename,"rb");
    if(bin == NULL){printf("Binary file open error\n"); return 0;}
    fseek(bin, 0, SEEK_END);
    int size = ftell(bin); //Here I get the wrong size
 // ......
}

这是我的主要功能:

int main()
{
     movie *v;
     database_add("movies.txt","db");
     v = database_read("db");
     return 0;
}

1 个答案:

答案 0 :(得分:2)

问题是,您永远不会刷新或关闭输出文件。一些数据将保留在缓冲区中。

这也会泄漏文件描述符,这也是很糟糕的。

添加到public class Imple { static{ System.loadLibrary(Core.NATIVE_LIBRARY_NAME); } public static void main(String[] args){ Imgcodecs imageCodecs = new Imgcodecs(); Mat mat = imageCodecs.imread("C:\\Users\\XYZ\\Desktop\\test.jpg"); LSBImageStego obj = new LSBImageStego(mat); String message = "Hello World"; if(obj.checkEncodePossibility(message)){ System.out.println("OK"); }else{ System.out.println("NO"); } Mat encodedImage = obj.encodeImage(message).clone(); imageCodecs.imwrite("C:\\Users\\XYZ\\Desktop\\test_ENCODED.jpg" ,encodedImage ); Mat mat2 = imageCodecs.imread("C:\\Users\\XYZ\\Desktop\\test_ENCODED.jpg"); // While debugging the Below function,I found that the Changed Pixel values were not being written back to the Disk obj.decodeImage(mat2); // In the above method,as part of debugging,I'm printing the Pixel values to the console. } } 函数的末尾:

database_add