3

I am writing a C library. I want to return the contents of a file from this function to the caller.

How can I convert the file contents to char[]?

fopen is crashing since I am using perl.h in my C code. Is there any other way to convert file into a char array apart from opening & reading the file?

Here is my code:

FILE* fp = fopen("console.txt", "r");
char message[1024];
strcpy(message,"\n");

char buf[80];
while(!feof(fp))
{
    fgets(buf, sizeof(buf)-1, fp);
    strcat(message, buf);
}
cppcoder
  • 22,227
  • 6
  • 56
  • 81
  • This might (partially) help: http://stackoverflow.com/questions/2029103/correct-way-to-read-a-text-file-into-a-buffer-in-c – Patrick B. Nov 25 '11 at 17:19

4 Answers4

2
  1. Get the file size (see How can I get a file's size in C?)
  2. Allocate memory to store contents of the file (see malloc).
  3. Read contents of the file into allocated memory (see read).
  4. Return a pointer and a length of data in bytes to the user.

Don't forget to check for errors in between those steps.

Community
  • 1
  • 1
1

Try this code. The function returns the string with file content, just print it.

    #include <stdio.h>
    #include <stdlib.h>

    char *readFile(char *filename)
    {
        char * buffer = 0;
        long length;
        FILE * f = fopen (filename, "r");
        if (f)
        {
            fseek (f, 0, SEEK_END);
            length = ftell (f);
            fseek (f, 0, SEEK_SET);
            buffer = malloc (length);
            if (buffer)
            {
                fread (buffer, 1, length, f);
            }
            fclose (f);
        }
        return buffer;
    }

    int main()
    {
       char *content=readFile("D://test1.xml");
       printf("%s",content);
       return 0;
    }
1

You need to do a few things

  • Determine size of file (checkout fstat/stat)
  • You need to malloc enough memory to hold the file
  • You can then use fread to read the conents of the file into your array (dont forget to open the file in binary mode)
  • Return you pointer (and dont forget that it has to be freed after by the function caller)
Adrian Cornish
  • 23,227
  • 13
  • 61
  • 77
0

Bit more information is required to give a good answer as the contents and nature of the file is required.

But generally,

If it is a text file see the stdio library - you can get the length, create an array and fill it. Otherwise (binary files) parsing it would be a good idea and return a data structure - a lot more useful

Ed Heal
  • 59,252
  • 17
  • 87
  • 127