2011-11-30 260 views
7
#include <iostream> 
#include <fstream> 

using namespace std; 

class info { 

private: 
    char name[15]; 
    char surname[15]; 
    int age; 
public: 
    void input(){ 
     cout<<"Your name:"<<endl; 
      cin.getline(name,15); 
     cout<<"Your surname:"<<endl; 
     cin.getline(surname,15); 
     cout<<"Your age:"<<endl; 
     cin>>age; 
     to_file(name,surname,age); 
    } 

    void to_file(char name[15], char surname[15], int age){ 
     fstream File ("example.bin", ios::out | ios::binary | ios::app); 
    // I doesn't know how to fill all variables(name,surname,age) in 1 variable (memblock) 
     //example File.write (memory_block, size); 

File.close(); 
    } 

}; 

int main(){ 

info ob; 
ob.input(); 

return 0; 
} 

我不知道如何写一个以上的变量到一个文件,请帮助,我包括一个例子;)也许有更好的方法写入文件,请帮助我这对我来说很难解决。写入二进制文件

+2

题外话你的问题,但如果你调用'ob.input()'不止一次,你会发现一个bug在你的输入代码中。尝试在'cin >> age'之后添加'std :: cin.ignore(100,'\ n');''。 –

回答

15

对于文本文件,你可以每行轻松输出一个变量使用类似<<给您std::cout使用的。

对于二进制文件,您需要使用std::ostream::write(),它会写入一个字节序列。对于你的age属性,你需要reinterpret_cast这个到const char*并且写出尽可能多的字节来保存你机器结构的int。请注意,如果您打算在另一台计算机上读取此二进制日期,则必须考虑word sizeendianness。我还建议您在使用它们之前将namesurname缓冲区置零,以免最终在二进制文件中产生未初始化内存的人为影响。

此外,不需要将该类的属性传递给to_file()方法。

#include <cstring> 
#include <fstream> 
#include <iostream> 

class info 
{ 
private: 
    char name[15]; 
    char surname[15]; 
    int age; 

public: 
    info() 
     :name() 
     ,surname() 
     ,age(0) 
    { 
     memset(name, 0, sizeof name); 
     memset(surname, 0, sizeof surname); 
    } 

    void input() 
    { 
     std::cout << "Your name:" << std::endl; 
     std::cin.getline(name, 15); 

     std::cout << "Your surname:" << std::endl; 
     std::cin.getline(surname, 15); 

     std::cout << "Your age:" << std::endl; 
     std::cin >> age; 

     to_file(); 
    } 

    void to_file() 
    { 
     std::ofstream fs("example.bin", std::ios::out | std::ios::binary | std::ios::app); 
     fs.write(name, sizeof name); 
     fs.write(surname, sizeof surname); 
     fs.write(reinterpret_cast<const char*>(&age), sizeof age); 
     fs.close(); 
    } 
}; 

int main() 
{ 
    info ob; 
    ob.input(); 
} 

采样数据文件可能是这样的:

% xxd example.bin 
0000000: 7573 6572 0000 0000 0000 0000 0000 0031 user...........1 
0000010: 3036 3938 3734 0000 0000 0000 0000 2f00 069874......../. 
0000020: 0000          .. 
+0

谢谢!也许这有点超出范围,但有什么工具来检查二进制文件? –

+0

@MinhTran:是的,这是一个新问题。也许看看https://stackoverflow.com/tags/xxd/info? – Johnsyweb

5
File.write(name, 15); 
File.write(surname, 15); 
File.write((char *) &age, sizeof(age)); 
+0

如果我有超过1个int变量,例如'char name [15]; \t char姓氏[15]; \t int age,phone;'when wite'File.write(name,15); File.write(姓氏,15); File.write((char *)&age&phone,sizeof(age&phone));'?? – Wizard

+0

@ user1069874:不,你不能像这样连接它们,你必须单独写它们:'File.write(name,15); File.write(姓氏,15); File.write((char *)&age,sizeof(age)); File.write((char *)&phone,sizeof(phone));' – Dani

+0

也许更好'File.write((char *)this,sizeof(info));'? – Wizard