How can i copy the contents of a textf, pointed to by a pointer, to a char array (i.e. pointer -> char array)

StackOverflow https://stackoverflow.com/questions/23526967

  •  17-07-2023
  •  | 
  •  

Question

I am reading from a file, which, thanks to malloc, saves the content of the text file to *buffer. However, I wish to transfer the contents of file to a char array. How can I accomplish this?

Here is my code so far:

#define LENGTH_OF_INPUT 49

FILE *FP = fopen("InputString.txt", "r");

char *buffer;
char InputString;

fseek(FP, 0L, SEEK_END);
s = ftell(FP);
rewind(FP);
buffer = (char*) malloc(s); /* buffer now is the content of the file */

if (buffer != NULL) /* If buffer was allocated... i.e the file exists*/
    {
    fread(buffer, s, 1, FP);
    fclose(FP); /* Must.. Close.. File.. */

    FP = NULL; /* For decaying pointer?? */

for (sizeofbuffer = 0; *buffer != '\0'; ++sizeofbuffer)
{
    *buffer++;
}

if (sizeofbuffer == LENGTH_OF_INPUT - 1 ) /* Check if the length of the string = 48 */
    {
        /* Correct length! */

        /* Also need to reset *buffer so that this for loop copies from the first letter */

        for (i = 0; *buffer != '\0' ; ++sizeofbuffer) /* Save to InputString*/
        {
            /* CODE NEEDS TO GO HERE!! */
        }
    }

I don't want to use strcpy in case the char array contains an early '\0'

EDIT: I found this http://www.cplusplus.com/forum/general/4107/; don't understand it though (is it even relevant?)

Était-ce utile?

La solution

Change this:

buffer = (char*)malloc(s);

To this:

buffer = (char*)malloc(s+1);
buffer[s] = 0;

And return buffer after you close the file; the rest of the code is redundant. In addition to that, don't forget to free the memory pointed by buffer at some later point in the execution of your program.


The purpose of buffer[s] = 0 is for you to be able to pass it to string functions. A few examples:

printf("%s",buffer);
strcpy(buffer2,buffer);
strcat(buffer2,buffer);
if (strcmp(buffer2,buffer) == 0) ...

Even if you're not interested in that, you still need a method with which you can detect the end of the string which is stored in the memory pointed by buffer. The answer above suggests the method of setting buffer[s] to a 0 (null) character. Alternatively, you can simply use the value of s itself. However, if you choose this method, then you'll have to maintain both buffer and s in a structure.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top