Сбой файла при открытии

в образовательных целях я пишу небольшую программу шифрования (не настоящее шифрование). Я реструктурировал программу, так что весь мой код находится в основном, чтобы упростить себе задачу.

Мой незашифрованный файл не работает. Я не знаю почему. Вот что я знаю до сих пор.

  1. Использование Xcode
  2. Протестированные операторы путем переключения порядка открытия (и тестирования) файлов, чтобы убедиться, что только незашифрованный файл не работает: это
  3. Перейдите к этапам сборки >> Копировать файлы >> Добавить файл, добавив оба файла в Абсолютный путь
  4. Я проверил правописание файлов и свой код
  5. На всякий случай снова изменил порядок, но незашифрованный файл все еще не работает.
  6. Очищены все флаги, которые могут быть там случайно
  7. Перемотать позиции чтения/записи файлов

Вот мой код целиком.

//  This program reads the contents of a file, encrypts it, and write the contents into a separate file.


#include <iostream>
#include <fstream>
#include <cctype>
#include <cstring>
#include <cmath>

using namespace std;

// Global Constants
const int POSITIVE_INT_LIMIT = 10;
const int NEGATIVE_INT_LIMIT = -10;
const int SLOPE_NEGATIVE = -1;
const int SLOPE_POSITIVE = 1;
const int STEP = 1;

int main() {

    int amplitude = 0, slope = SLOPE_NEGATIVE; //Set initial amplitude and slope.

    int streamSize = 1;

    char ch, cy;
    char *chPtr = &cy; // Initialize and assign char pointer.

    //open an unencrypted file to read from
    fstream unEncryptedFile;
    unEncryptedFile.open("testA", ios::in | ios::binary);

    //open a file to write encrypted info
    fstream cryptFile;
    cryptFile.open("testB", ios::out | ios::binary);

    //Clear flags previous set, just in case
    unEncryptedFile.clear();
    cryptFile.clear();

    //Rewind the files, just in case
    unEncryptedFile.seekg(0L, ios::beg);
    cryptFile.seekp(0L, ios::beg);

    if (unEncryptedFile.fail()) {
        cout << "Error opening read file." << endl;
        exit(1);
    }

    if (cryptFile.fail()) {
        cout << "Error opening write file." << endl;
        exit(1);
    }



    /*      Encryption pattern inside while-loop.

     limit>     10                             *
                9                             * *
                8                            *   *
                7                           *     *
                6                          *       * 
                5                         *         *
                4                        *           *
                3                       *             *
                2                      *               *
                1                     *                 *
     start>     0*2345678901234567890*2345678901234567890* -- < one hertz (cycle)
               -1 *                 *
               -2  *               *   (Number line: each integer represents a single while-loop cycle.)
               -3   *             *
               -4    *           *
               -5     *         *
               -6      *       *
               -7       *     *
               -8        *   *
               -9         * *
     limit>    -10         *

     */
    /*************************************************************
     The pattern above depictes a single character
     being read, and then the value of amplitude is added to it.

     *************************************************************/

    while (!unEncryptedFile.fail()) {

        ch = unEncryptedFile.get(); // Get the next character in the file.

        cout << ch << endl; // test for proper read

        if (amplitude > NEGATIVE_INT_LIMIT && slope == SLOPE_NEGATIVE) {
            amplitude -= STEP;
            cy = ch + amplitude;
            cryptFile.write(chPtr, streamSize); //Adjusted character value, cy, is written to file.

        } else if (amplitude <= NEGATIVE_INT_LIMIT){
            slope = SLOPE_POSITIVE;
            amplitude = NEGATIVE_INT_LIMIT;
            cy = ch + amplitude;
            cryptFile.write(chPtr, streamSize); //Adjusted character value, cy, is written to file.

        } else if (amplitude < POSITIVE_INT_LIMIT && SLOPE_POSITIVE){
            amplitude += STEP;
            cy = ch + amplitude;
            cryptFile.write(chPtr, streamSize); //Adjusted character value, cy, is written to file.

        } else if (amplitude >= POSITIVE_INT_LIMIT){
            slope = SLOPE_NEGATIVE;
            amplitude = POSITIVE_INT_LIMIT;
            cy = ch + amplitude;
            cryptFile.write(chPtr, streamSize); //Adjusted character value, cy, is written to file.
        }

    }

    //Files are closed.
    unEncryptedFile.close();
    cryptFile.close();



    return 0;
}

person NonCreature0714    schedule 02.12.2015    source источник
comment
Рассмотрим [stackoverflow.com/questions /24097580/ в качестве передового метода проверки ошибок и используйте while (!unEncryptedFile.eof()) в качестве проверки конца файла.   -  person ankhzet    schedule 02.12.2015
comment
@ankhzet, что интересно, использование while (!unEncryptedFile.eof()) создало бесконечный цикл с выходом \377 ... Я не знаю, что с этим делать.   -  person NonCreature0714    schedule 02.12.2015
comment
Вы пробовали unEncryptedFile.read(&ch, 1); вместо ch = unEncryptedFile.get(); в сочетании с while (!unEncryptedFile.eof())?   -  person ankhzet    schedule 02.12.2015
comment
@ankhzet, я только что попробовал. Тот же результат. Но вот что интересно - \377 и \376 продолжают отображаться как значения ch и cy. Это escape-символы, которые означают eof. Может быть, по какой-то причине перед чтением любого текста есть escape-символ eof?   -  person NonCreature0714    schedule 02.12.2015
comment
@ankhzet, вот сообщение о \377 - хотя оно не объясняет, почему в world моя позиция чтения начинается с eof, даже после явного размещения ее в начале файла   -  person NonCreature0714    schedule 02.12.2015
comment
Возможно, что файл, открытый с помощью unEncryptedFile.open("testA", ios::in | ios::binary), на самом деле пуст. Возможно, когда приложение запускается, "testA" расширяется в какое-то другое местоположение файла, чем вы предполагали. Возможно, указание абсолютного пути поможет...   -  person ankhzet    schedule 02.12.2015
comment
Кстати, if (amplitude < POSITIVE_INT_LIMIT && SLOPE_POSITIVE), я думаю, это должно быть if (amplitude < POSITIVE_INT_LIMIT && slope == SLOPE_POSITIVE)   -  person ankhzet    schedule 02.12.2015


Ответы (1)


вам нужно указать расширение файла с именем файла при открытии файла

int main() {

    int amplitude = 0, slope = SLOPE_NEGATIVE; //Set initial amplitude and slope.

    int streamSize = 1;

    char ch, cy;
    char *chPtr = &cy; // Initialize and assign char pointer.

    //open an unencrypted file to read from
    fstream unEncryptedFile;

    unEncryptedFile.open("testA.txt", ios::in | ios::binary);

Я попробовал ваш код с этим, и он работает.

person Shvet Chakra    schedule 02.12.2015
comment
Я только что попробовал его с расширениями, и он у меня не работает... Перезапуск компилятора... И он не перестает открываться... Итак, **что-то происходит с моим компилятором** :/ - person NonCreature0714; 02.12.2015