使用fread读入int缓冲区 [英] using fread to read into int buffer

查看:276
本文介绍了使用fread读入int缓冲区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以使用fread将数据读入整数缓冲区。
我看到fread()以void *作为第一个参数。所以我不能只是传递一个整数
缓冲区(typecast到void *),然后使用这个来读取我想从文件中多少字节,只要缓冲区足够大?

I would like to know if I can use fread to read data into an integer buffer. I see fread() takes void * as the first parameter. So can't I just pass an integer buffer (typecast to void *) and then use this to read howmuchevery bytes I want to from the file, as long as the buffer is big enough ?

ie。不能执行:

  int buffer[10];
  fread((void *)buffer, sizeof(int), 10, somefile);
  // print contents of buffer
  for(int i = 0; i < 10; i++)
  cout << buffer[i] << endl;

这里有什么问题?

推荐答案

如果你使用类似 fwrite (binarywrite)。如果文件是人类可读的(你可以用文本编辑器打开它,看看有意义的数字),你可能想要 fscanf / code>。

This should work if you wrote the ints to the file using something like fwrite ("binary" write). If the file is human-readable (you can open it with a text editor and see numbers that make sense) you probably want fscanf / cin.

这篇关于使用fread读入int缓冲区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆