проверить, существует ли файл, не открывая его c ++ на Xcode 4 - PullRequest
0 голосов
/ 21 марта 2012

Я немного запутался с проверкой, чтобы увидеть, существует ли файл ofstream для записи в него.В Xcode для Mac 10.5.8 я смог написать

testStream.open(fileName.c_str());
   if (testStream.good()) {
            cout << "The file already exists, please choose another" 
            << endl;
            testStream.clear();
            testStream.close();
    }

Но в Xcode 4, когда он проходит мимо команды open, он создает пустой файл, поэтому оператор if всегда будет срабатывать.Есть ли лучший способ проверить, существует ли файл?Я попытался изменить его на:

testStream.open(fileName.c_str(), iOS::out | iOS::nocreate);

Но компилятор получает ошибку, которая говорит, что нет элемента с именем nocreate.Помогите, пожалуйста??

Если это поможет, вот весь компилируемый код (моя программа - Цезарь):

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>
using namespace std;
string getInput ();
ifstream * openInFile ();
int getShiftValue ();
void menu ();
string shiftCharacters (int shiftNum, ifstream * inFile);
string getOutput ();
ofstream * openOutFile ();
void printSentence (string outData, ofstream * outFile);
int main() {
    ifstream * inFile;
    ofstream * outFile;
    string inFileName, outFileName, outData; 
    int shiftNum = 0;
    menu();
    inFile = openInFile(); 
    shiftNum = getShiftValue();
    outData = shiftCharacters(shiftNum, inFile);
    inFile->clear();
    inFile->close();
    outFile = openOutFile();
    printSentence(outData, outFile);
    outFile->clear();
    outFile->close();
    return 0;
}
// Input Functions
string getInput () {
    cout << "Enter an input file name: "; 
    string inFileName;
    getline(cin, inFileName); 
    return inFileName;
}
string getOutput () {
    string outFileName;
    cout << "Enter an output file name: ";
    getline(cin, outFileName);
    return outFileName;
}
ifstream * openInFile () {
    ifstream * inFile;   
    bool isGood = false; 
    string inFileName;    
    inFile = new ifstream;
    do {   
        inFileName = getInput();
        inFile->open(inFileName.c_str());
       if (inFile->fail()) { 
           cout << "Couldn't open file" << endl;
        }
       else {
           isGood = true;
       }
    }
    while (!isGood);
   return inFile;
}
ofstream * openOutFile () {
    ofstream testStream; 
    ofstream * outFile;   
    bool isUnique = false; 
    string fileName;
   do {   
       fileName = getOutput();
       testStream.clear(); 
       testStream.open(fileName.c_str());
       if (testStream.good()) {
            cout << "The file already exists, please choose another" 
            << endl;
            testStream.clear();
            testStream.close();
        }
    else {
            isUnique = true;
            testStream.clear();
            testStream.close();
    }
}
while (!isUnique);
outFile = new ofstream;
outFile->open(fileName.c_str());
return outFile;
}
int getShiftValue () {
    int shiftNum;
    string trash;
    cout << "Please enter shift value: ";
    cin >> shiftNum;
    getline(cin, trash); 
    return shiftNum;
}

// Data manipulation functions 
 string shiftCharacters (int shiftNum, ifstream * inFile){
    string inData, outData; 
    char outChar;
    int idx = 0;
    stringstream outSentence; 
    while (getline(* inFile, inData)) {
        for (idx = 0; idx <= inData.length() - 1; idx++) {
            if (inData[idx] >= 'a' && inData[idx] <= 'z') {
                outChar = (((inData[idx] - 'a') + shiftNum) % 26) +
                'a';
                outSentence << outChar;
            }
            else if (inData[idx] >= 'A' && inData[idx] <= 'Z') {
                outChar = (((inData[idx] - 'A') + shiftNum) % 26) +
                'A';
                outSentence << outChar;
            }
            else {
                outChar = inData[idx];
                outSentence << outChar;
        }
    }
 }
     outSentence >> outData;
     return outData;
 }
// Output funcitons
void menu () {
    cout << "C A E S A R  C Y P H E R  P R O G R A M" << endl
     << "========================================" << endl;
   return;
}
void printSentence (string outData, ofstream * outFile) {
    int idx = 0;
    char outChar;
    stringstream outString;
    outString << outData;
    for (idx = 0; idx <= outData.length() - 1; idx++) {  
        outChar = outString.get();
        outFile->put(outChar); 
    }
}

1 Ответ

0 голосов
/ 21 марта 2012

Вы можете сначала открыть файл в режиме ввода (режим ios_base::in), чтобы проверить, существует ли он. Или с помощью системного вызова stat.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...