C ++如何使用FILE读取文件 [英] C++ how to read file using FILE

查看:263
本文介绍了C ++如何使用FILE读取文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要知道如何使用c ++中的FILE读取文件创建,以回读其创建的文件程序吗?我能够从fstream读取文件,但我希望使用其他文件命令来读取不同的类型.

文件* f

int main()
{
f = f.open("tmp.dat","a");
fwrite(???,sizeof(short),1,f);
fclose();
}

I need to know how to read file create using the FILE in c++ to read back on the program of the files it makes? I able to read files from fstream but i look to use the other file commands to read a different types.

FILE *f

int main()
{
f = f.open("tmp.dat","a");
fwrite(???,sizeof(short),1,f);
fclose();
}

推荐答案

永远不要在C ++中使用FILE.这是一个C构造.您应该使用iostream,特别是ifstream和ofstream.
You should never use FILE in C++. It''s a C construct. You should use iostreams, specifically, ifstream and ofstream.


Cristian是正确的.无需做您想问的事情.但是,要以C方式读取文件,您需要这样的内容:

Cristian is right. There is no need to do what you''re asking about. However, to read file the C way, you need something like this:

#include <stdio.h>
//..

FILE * f;
char ch;
char line[80];

f = fopen ("tmp.dat", "r");
if (f == NULL) { /*... as this is still C++, throw exception */ }

ch = fgetc(f);
//... and so on

//this is how to read line-by-line:
while(fgets(line, 80, f) != NULL) { /* use line */ }

fclose(f);



您可以自己学习更多功能.这将使您对所涉及的内容有所了解: http://en.wikipedia.org/wiki/C_file_input/output [ ^ ].

—SA



There are more function you can learn by yourself. This will get you an idea on what''s involved: http://en.wikipedia.org/wiki/C_file_input/output[^].

—SA


这篇关于C ++如何使用FILE读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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