2012-02-09 5 views
1

Visual C++を使用してjpgファイル全体をバイナリモードで読み込もうとしています。次のようにコードは次のとおりです。C++を使用してバイナリモードでファイル全体を読む

FILE *fd = fopen("c:\\Temp\\img.jpg", "rb"); 
if(fd == NULL) { 
    cerr << "Error opening file\n"; 
    return; 
} 

fseek(fd, 0, SEEK_END); 
long fileSize = ftell(fd); 
int *stream = (int *)malloc(fileSize); 
cout << fileSize << '\n'; 
fseek(fd, 0, SEEK_SET); 
int bytes_read = fread(stream, fileSize, 1, fd); 
printf("%i\n", bytes_read); 
fclose(fd); 

問題はbytes_readは常に1であるfileSize変数は、ファイルの正しいサイズを含んでいることです。だから私はなぜbytes_readが常に1であり、fileSize ..と等しくないのか分かりません。

+0

参照:http://stackoverflow.com/questions/116038/what-is-the-best-way-to-slurp-a-file-into-a-ststring-in-c –

答えて

2
int n_read = fread(stream, fileSize, 1, fd); 

あなたが持っているサイズのチャンクの数を返します。この場合、C標準のセクション7.21.8.1に1

ルック: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1548.pdf(ページ334)

だから、読み取ったバイト数を取得するためにfileSizen_readを乗算する必要があります。

+1

逆に、 'fread (stream、1、fileSize、fd) 'は読み込んだバイト数を返します。 –

+0

はい。私はこの答え+あなたのコメントはポケモンのために十分であるべきだと思います。 –

1
RETURN VALUE 
     fread() and fwrite() return the number of items successfully read or 
     written (i.e., not the number of characters). If an error occurs, or 
     the end-of-file is reached, the return value is a short item count (or 
     zero). 

あなたはサイズfileSizeの1つの項目を読むためにそれを告げ、それがなかったです。

2

あなたはバイトの数は、あなたがそうのような引数を切り替える必要がある読みたい場合は:

int bytes_read = fread(stream, 1, fileSize, fd); 
1

man 3p freadから:

のfread()とfwriteの()に成功した項目の数を返します(すなわち、文字数ではなく)読み書きされます。エラーが発生した場合、またはファイルの終わりに達した場合、戻り値は短い項目 個(またはゼロ)です。

あなたは1ファイル長を読むように言った、それはそれが読んだものです。 C++で

0

、あなたはとして慣用読書スタイルが付属しているstd::ifstreamを使用することができます。

std::ifstream file("file.bin", std::ifstream::binary); //binary mode! 
std::istream_iterator<char> begin(file), end); //setup iterators! 
std::vector<char> v(begin,end); //read all data into a vector! 
//v contains the binary data, which you can use from now on 

//you can get the pointer to the data as 
char *buffer = &v[0]; 
size_t sizeOfBuffer = v.size(); 
//you can use buffer and sizeOfBuffer instead of v. 

//just remember that the lifetime of buffer is tied with the lifetime of v 
//which means, if v goes out scope, the pointer `buffer` will become invalid 

あなたは上記のスニペットでのコメントを読んで願っています。 :-)あなたは1つのバイトを読み取るために、それを言っているのfreadへのお電話で

+0

'istream_iterator'は空白をスキップして、書式付き入力を読み込みます。 'istreambuf_iterator'、おそらく? –

+0

@Rob:私はそう思います。 'istream_iterator'はデータを読み込みません。 'std :: ifstream :: binary'モードで開かれるので、ストリームオブジェクト自体が読み込むデータを*反復するだけです。この場合、空白も読み込まれます。 – Nawaz

+0

...多分私は間違っています。私はそれを確認しなければならない。 – Nawaz

0

...

は、これは以下のようになりますのfread(ストリーム、1、ファイルサイズ、FD);

関連する問題