0

I'm trying to determine how big a file i'm reading is in bytes so I used Fseek to jump to the end and it triggered the error: file.exe has triggered a breakpoint. Heses the code: FileUtils.cpp: #include "FileUtils.h"

namespace impact {

    std::string read_file(const char* filepath)
    {
        FILE* file = fopen(filepath, "rt");
        fseek(file, 0, SEEK_END);
        unsigned long length = ftell(file);
        char* data = new char[length + 1];
        memset(data, 0, length + 1);
        fseek(file, 0 ,SEEK_SET);
        fread(data, 1, length, file);
        fclose(file);

        std::string result(data);
        delete[] data;
        return result;
    }

}

FileUtils.h:

    #pragma once
#include <stdio.h>
#include <string>
#include <fstream>


namespace impact {
    std::string read_file(const char* filepath);
}

If more info is required just ask me for it I would be more than happy to provide more!

  • 1
    `FILE* file = fopen(filepath, "rt");` -- You did not check if the file opened successfully. – PaulMcKenzie Feb 27 '20 at 18:27
  • For more details about how to determine the size of a file using fstream,I suggest you could refer to the links: https://stackoverflow.com/questions/2409504/using-c-filestreams-fstream-how-can-you-determine-the-size-of-a-file https://stackoverflow.com/questions/5840148/how-can-i-get-a-files-size-in-c – Jeaninez - MSFT Feb 28 '20 at 08:42

1 Answers1

0

You are doing this in the C way, C++ has much better (in my opinion) ways of handling files.

Your error looks like it may be caused because the file didn't open correctly (you need to check if file != nullptr).

To do this in C++17 you should use the standard library filesystem (Note: You can also do this with C++11 experimental/filesystem using std::experimental::filesystem namespace)

Example:

std::string read_file(const std::filesystem::path& filepath) {
    auto f_size = std::filesystem::file_size(filepath);
    ...
}

Additionally to read a file in C++ you do not need to know the size of the file. You can use streams:

std::string read_file(const std::filesystem::path& filepath) {
   std::ifstream file(filepath); // Open the file

   // Throw if failed to open the file
   if (!file) throw std::runtime_error("File failed to open");

   std::stringstream data; // Create the buffer
   data << file.rdbuf(); // Read into the buffer the internal buffer of the file
   return data.str(); // Convert the stringstream to string and return it
}

As you can see, the C++ way of doing it is much shorter and much easier to debug (helpful exceptions with descriptions are thrown when something goes wrong)

Object object
  • 1,939
  • 10
  • 19