C program .txt into char*?

Is it possible to convert a FILE with .txt into a char*?

✅ Answers

? Favorite Answer

  • Sure. Not only possible, but fairly easy–especially if you know ahead of time that the file is of a manageable size.

    There are many ways to open a file, but as I’m not sure which functions you’re used to I’ll list a few ways. As a Windows programmer I tend to use CreateFile and ReadFile.

    Here’s the flow (without parameters) for several different sets of functions.

    CreateFileEx() // open the file

    size = GetFileSize() //get the size of the file.

    fileChars = new char[size];

    ReadFile();

    And another way to do this:

    fopen() //open the file

    size = _filelength() //get the size of the file.

    fileChars = new char[size];

    fread() //read data

    and yet another way:

    _open

    size = _filelength()

    fileChars = new char[size];

    _read();

    Pick the one that looks most familiar to you. You can read up on any of these functions using MSDN at http://msdn.microsoft.com/

    Good luck.

  • A file can either be binary or text based.

    Binary means that the numbers are actually numbers, not what they appear if you were displaying them in text on the screen.

    Text based means that you would be using a file that only has the numbers in an easily readable text file that you could open in Notepad or other type of text editor.

    The C type “char *” is simply a way to store text information in a string. So, if you allocated enough of a string then you could read an entire file into a simple “char *” variable.

    FILE *fptr = fopen(“myfile.txt”, “r”);

    char *myfileStr[]; /* Note that the here and below should be the maximum size your file is taking up on the disk */

    size_t freadSize;

    if (fptr)

    {

       freadSize = fread(&myfileStr, sizeof(char), , fptr);

       fclose(fptr);

    }

  • Yes , fread() takes a FILE pointer and it puts one char from a txt file into a char* type buffer that you feed it.

  • I trust Jeff’s answer above… the only factor you need to replace is char call; to be a char array and supply it a length. Your software works completely after that little replace.

  • Sorry, I’m a Java/C++ guy, but I think the procedure is fairly similar.

    You’d have to use an input file stream. Open the file using fopen() then read the contents using fscanf().

    I looked up a website that may be of some use to you.

    Source(s): http://www.cs.bu.edu/teaching/c/file-io/intro/

  • Leave a Comment