How to Copy a .Txt File to a Char Array in C++

Copy text file into char* array

You are calculating the length of the file but you don't use this information in
any way.

char *f_array[256];

This is an array of dimension 256 of pointers to char. f_array[i] is
uninitialized and it's pointing into the digital nirvana, passing it to
fscanf yields undefined behaviour. You would need to declare it as something
like this:

char f_array[255][255];

But then you are limiting yourself to max 255 strings, you are not storing it
into a single string. Also you are storing max. 255 words. Use fgets or
fread to get the whole content at once.

char file[f_length + 1];

rewind(fp);

fread(file, f_length, 1, fp);

file[f_length] = 0; // terminate the string

printf("Whole file is: %s\n", file);

Here you are storing the whole file in an array of chars. Also after setting
the file at the end, you'll need to rewind the file to the beginning, otherwise
you are not reading anything.

How to copy a .txt file to a char array in c++

With

myfile >> myArray[i]; 

you are reading file word by word which causes skipping of the spaces.

You can read entire file into the string with

std::ifstream in("FileReadExample.cpp");
std::string contents((std::istreambuf_iterator<char>(in)),
std::istreambuf_iterator<char>());

And then you can use contents.c_str() to get char array.

How this works

std::string has range constructor that copies the sequence of characters in the range [first,last) note that it will not copy last, in the same order:

template <class InputIterator>
string (InputIterator first, InputIterator last);

std::istreambuf_iterator iterator is input iterator that read successive elements from a stream buffer.

std::istreambuf_iterator<char>(in)

will create iterator for our ifstream in (beginning of the file), and if you don't pass any parameters to the constructor, it will create end-of-stream iterator (last position):

The default-constructed std::istreambuf_iterator is known as the end-of-stream iterator. When a valid std::istreambuf_iterator reaches the end of the underlying stream, it becomes equal to the end-of-stream iterator. Dereferencing or incrementing it further invokes undefined behavior.

So, this will copy all characters, starting from the first in the file, until the next character is end of the stream.

Reading the whole text file into a char array in C

FILE *fp;
long lSize;
char *buffer;

fp = fopen ( "blah.txt" , "rb" );
if( !fp ) perror("blah.txt"),exit(1);

fseek( fp , 0L , SEEK_END);
lSize = ftell( fp );
rewind( fp );

/* allocate memory for entire content */
buffer = calloc( 1, lSize+1 );
if( !buffer ) fclose(fp),fputs("memory alloc fails",stderr),exit(1);

/* copy the file into the buffer */
if( 1!=fread( buffer , lSize, 1 , fp) )
fclose(fp),free(buffer),fputs("entire read fails",stderr),exit(1);

/* do your work here, buffer is a string contains the whole text */

fclose(fp);
free(buffer);

Reading text file into char array

Possible duplicate of Reading the whole text file into a char array in C.


Your problem : fscanf with the "%s" format will read up to the first whitespace encountered.

Possible solution (error-checking is omitted for conciseness) :

#include <stdio.h>  /* printf */
#include <stdlib.h> /* fopen, fseek, ... */

char *buffer = NULL;
size_t size = 0;

/* Open your_file in read-only mode */
FILE *fp = fopen("your_file_name", "r");

/* Get the buffer size */
fseek(fp, 0, SEEK_END); /* Go to end of file */
size = ftell(fp); /* How many bytes did we pass ? */

/* Set position of stream to the beginning */
rewind(fp);

/* Allocate the buffer (no need to initialize it with calloc) */
buffer = malloc((size + 1) * sizeof(*buffer)); /* size + 1 byte for the \0 */

/* Read the file into the buffer */
fread(buffer, size, 1, fp); /* Read 1 chunk of size bytes from fp into buffer */

/* NULL-terminate the buffer */
buffer[size] = '\0';

/* Print it ! */
printf("%s\n", buffer);

character by character reading from a txt file, and writing to another file in C?

FILE* f = fopen(f, "r"); 

This is obvious typo. It should be fopen("inputfile", "r").

int* x; 
if (x == NULL) { return NULL; }

x is not initialized. That means it could be NULL (zero) or it could be any other random value. You can't test it at this point.

while (1) {
...
int* x = calloc(i, sizeof(double));
}

Here you have declared a different pointer with the same name. The second x is a different variable because it's in a different scope (when you put variables inside {} the scope changes)

The second x allocates memory then it is lost in the next iteration of the loop. This leads to significant memory leak.

sizeof(double) is not applicable. If you intend to store in a char buffer, first you have to know how many characters there are in the file. It's impossible to know that before you read the file.

To get around this problem, you can go through the file once and count the characters, or you can check the file size.

Once you allocate enough memory, you can use fread/fwrite to read the entire file.

int main(void)
{
FILE* fin = fopen("input.txt", "r");
if (!fin) { perror("input error"); return 0; }
FILE* fout = fopen("output.txt", "w");
if (!fout) { perror("fout error"); return 0; }

fseek(fin, 0, SEEK_END); //go to the end of file
size_t filesize = ftell(fin); //get file size
fseek(fin, 0, SEEK_SET); //go back to the beginning

//allocate enough memory
char* buffer = malloc(filesize * sizeof(char));

//read one character at a time (or `fread` the whole file)
size_t i = 0;
while (1)
{
int c = fgetc(fin);
if (c == EOF) break;

//save to buffer
buffer[i++] = (char)c;
}

//write one character at a time (or `fwrite` the whole file)
for (i = 0; i < filesize; i++)
fputc(buffer[i], fout);

free(buffer);
fclose(fin);
fclose(fout);
return 0;
}


Related Topics



Leave a reply



Submit