使用xCode在C ++中创建,管理和删除文件

时间:2015-11-11 09:31:28

标签: c++ xcode

我是一名相当新手的程序员,在高中二年级开了几门课程,我遇到了一些问题。所以让我们继续吧。

长话短说,我已经学会了如何创建文件:

#include <iostream>
#include <fstream>
using namespace std;

int main(){
    string Test;
    ofstream file;
    file.open("Cookies.txt");
    if(file.is_open()){
        file << "I have cookies! :3" << endl;
        file.close();
    }
    else{
        cout << "Error. No file has been created." << endl;
    }
    ifstream cookies;
    cookies.open("Cookies.txt");
    if(cookies.is_open()){
        cout << cookies.rdbuf();
    }

    return 0;
}

但我现在的问题是,我如何“使用”此文件中的内容?就像我想保存变量一样,或者将“我有cookie!:3”导入主程序中的字符串变量。因为它应该是可能的似乎是合理的,我还没有发现如何。

另外,如何删除我创建的文件?因为像 file.delete( “cookie.txt的”);根本不起作用。

提前感谢您的回答。 最好的问候,Staggen。

1 个答案:

答案 0 :(得分:0)

您可以使用ifstream(输入文件流)而不是ofstream(输出文件流),使用>>以类似的方式从文件中读取文件操作员读入变量。它默认为一次读取一个值,而对于转换为&#34;单词&#34;的字符串:

所以:

if (cookies.is_open())
{
  std::string word;

  while (cookies >> word) // read from the filestream into "line"
  {
    std::cout << "Read a word: " << line << std::endl;
  }
}

这是一种读取不同数据类型的相当好的方法。

要阅读整行,您可以使用带有换行符的std::getline()作为分隔符:

if (cookies.is_open())
{
  std::string line;

  while (std::getline(cookies, line, '\n'))
  {
    std::cout << "Read a line: " << line << std::endl;
  }
}

删除文件是与读取/写入文件无关的操作系统级活动。 <cstdio>标题包含std::remove(),将删除文件。

@anderas是对的;你应该通过文件I / O上的a tutorial来学习或巩固基础知识。