Приложение C ++, которое считывает имя файла из командной строки, использует метод read () для чтения содержимого файла - PullRequest
0 голосов
/ 26 мая 2020

У меня есть этот код, но после ввода имени из командной строки он начинает работать, но на выходе получается нескончаемый странный массив символов. Проблема, которую я пытался решить, гласит: Напишите приложение C ++, которое считывает содержимое файла с помощью метода read (). Полученные данные отображаются на экране. Проверяйте состояние системы после каждой операции чтения. Имя файла читается из командной строки. Мой код:

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

int main(int argc, char* argv[])
{
    char arr[15];
    ifstream file;
    file.open(argv[1], ios::in); //filename read from the command line
    if (argc == 1)
    {
        cout << "Enter file name from command line!";
    }
    int readState = 0;
    while (!file.eof())
    {
        file.read(arr, 10); //reading the file's content
        if (file.good())
        {
            arr[10] = '\0';
            cout << arr;
            readState++; //checking the system's state after each read()
        }
        else
        {
            cout << arr;
        }
    }
    file.close();
    return 0;

}

Я также проверил, но файл не создается .. Если у вас есть какие-либо советы, как это исправить или как я могу сделать это как-то иначе помогло бы ..

Ответы [ 2 ]

1 голос
/ 26 мая 2020

эта версия работает, посмотрите изменения, которые я внес.

первый

Я проверяю, есть ли у меня путь, прежде чем пытаться его открыть

секунда

проверьте, открывается ли файл с помощью if_open

EDIT измените чтение на std :: getline

РЕДАКТИРОВАТЬ

добавить std :: ios :: out в открытый режим, чтобы создать файл, если он не существует

#include <stdio.h>
#include <iostream>

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

int main(int argc, char* argv[])
{
  char arr[15];
  ifstream file;
  if (argc == 1)// <- moved it before opening the file
  {
    cout << "Enter file name from command line!";
    return 0;
  }
  file.open(argv[1], ios::in|std::ios::out); //filename read from the command line and also create the file if it dosent exist
  if(!file.is_open()) // <- second change
  {
    std::cout << "file not opening\n";
    return 0;
  }

  int readState = 0;
  std::string line;
  while ( std::getline(file, string ) ) // <-- third fix
  {
    cout << arr;
    readState++; //checking the system's state after each read()
    }
    else
    {
      cout << arr;
    }
  }
  file.close();
  return 0;

}

также, не используйте с использованием пространства имен std

0 голосов
/ 27 мая 2020

Ладно, похоже, я смог исправить все ошибки. Итак, вот хороший код:

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

int main(int argc, char* argv[]) //using command line arguments
{
    char arr[15];
    ofstream wfile;
    if (argc == 1)
    {
        cout << "Enter file name from command line!";
        return 0;
    }

    cout << "Enter an array:";
    cin >> arr; //reading the array from KBD

    wfile.open(argv[1], ios::out);  //filename read from the command line
    if (!wfile)
    {
        cout << "File can't be opened!";
        exit(1);
    }
    else
        cout << "File created" << endl;
    wfile.write(arr, strlen(arr)); //write the array into file
    wfile.close(); //closing file 

    ifstream file;
    file.open(argv[1], ios::in); //opening the file to read from it
    if (!file.is_open()) //if file is not opened displays a message
    {
        cout << "File not opening\n";
        exit(1);
    }

    int readState = 0; //initializing the system state
    char *array;
    array = new char[10]; //allocating memory

    while (!file.eof())
    {
        file.read(array, 10); //using read() method
        for(int i=0;i<10;i++)
            cout << array[i]; //display the array from the file
        readState++;
    }

    cout <<"\nSystem state is:"<< readState; //checking system state
    delete[]array; //eliberating memory
    file.close(); //closing file
    return 0;

}

Кажется, проблема заключалась в том, что я ничего не вводил в файл

...