I am trying to write a program which reads all TXT file and copies into one specific array.But, the problem is white-space characters. If I use fscanf, I cannot get all TXT file into one array. How can I copy a TXT file into char array?
Asked
Active
Viewed 917 times
3 Answers
2
The standard library provides all the functions necessary to be able to read the entire contents of a file in one function call. You have to figure out the size of the file first, make sure you allocate enough memory to hold the contents of the file, then read everything in one function call.
#include <stdio.h>
#include <stdlib.h>
long getFileSize(FILE* fp)
{
long size = 0;
fpos_t pos;
fseek(fp, 0, SEEK_END);
size = ftell(fp);
fseek(fp, 0, SEEK_SET);
return size;
}
int main(int argc, char** argv)
{
long fileSize;
char* fileContents;
if ( argc > 1 )
{
char* file = argv[1];
FILE* fp = fopen(file, "r");
if ( fp != NULL )
{
/* Determine the size of the file */
fileSize = getFileSize(fp);
/* Allocate memory for the contents */
fileContents = malloc(fileSize+1);
/* Read the contents */
fread(fileContents, 1, fileSize, fp);
/* fread does not automatically add a terminating NULL character.
You must add it yourself. */
fileContents[fileSize] = '\0';
/* Do something useful with the contents of the file */
printf("The contents of the file...\n%s", fileContents);
/* Release allocated memory */
free(fileContents);
fclose(fp);
}
}
}

R Sahu
- 204,454
- 14
- 159
- 270
1
You could use fread(3)
to read everything from a stream like this:
char buf[1024];
while (fread(buf, 1, sizeof(buf), stream) > 0) {
/* put contents of buf to your array */
}

Lee Duhem
- 14,695
- 3
- 29
- 47
1
You can use the function fgetc(<file pointer>)
which returns a single character read from the file, if you use this function you should check if the read character is EOF

Andrea Gobetti
- 143
- 1
- 8