2014-07-12 27 views
1

我想讀一個文件按字節到一個數組,然後寫該陣列的數據在一個新文件反轉 (程序接管命令行參數文件名)更大。嘗試用txt文件 ,它的工作,但如果我嘗試在JPG文件上新文件比原來更大! 確定的文件大小保存在長尺寸;也是正確的jpg文件和寫循環 得到大小時間執行寫一個字符(字符是一個字節大,我是對的?)。 有誰知道輸出文件的大小如何大於*字節?fwrite的創建一個輸出文件,它是比輸入文件

這對我來說似乎不合邏輯!

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

int main(int argc,char* argv[]) 
{ 

FILE *file; 
char *buffer; 
long size; 
char filename[32]; 

if(argc>1) 
{ 
    //determine file size 
    file=fopen(argv[1],"r"); 
    fseek(file,0,SEEK_END); 
    size=ftell(file); 
    rewind(file); 
    if(size>33554432) //32MB 
    { 
    fclose(file); 
    return 0; 
    } 

    //create buffer and read file content 
    buffer=malloc(33554432); 
    fread(buffer,1,size,file); 
    fclose(file); 

    //create new file name and write new file 
    strcpy(filename,argv[1]); 
    strcat(filename,"_"); 
    file=fopen(filename,"w"); 
    { 
    long i; 
    for(i=size-1;i>=0;i--) 
    { 
    fputc(buffer[i],file); 
    } 
    } 
    fclose(file); 
    free(buffer); 

} 
return 0; 
} 
+1

無法重現(Linux,64位,使用gcc)。你使用的是什麼操作系統和編譯器?的[什麼是在的fopen r和RB之間的差異] – McLovin

+2

可能重複(http://stackoverflow.com/questions/2174889/whats-the-differences-between-r-and-rb-in-fopen) –

回答

4

您收到的暗示某物的評論:換行符\n與其他系統相比,在文本模式下的工作方式不同在Windows上。

fputc('\n', file)如果在文本模式「w」中打開file,則實際上會寫入兩個字節,就像您執行的操作fwrite("\r\n", 1, 2, file)一樣。這意味着對於由fread讀取的任何\n字節,您將寫回兩個字節。

如果您想要回寫二進制數據,則需要使用模式"wb"fopen()打開輸出文件。您還需要打開它才能以二進制模式讀取,"rb"

+0

「WB」和「RB」解決了它 – user3832921