Copying file pointer into array - c

Here, I am trying to read from a text file, copy this file into an array, then I want to write the array to another text file. This is not copying into the array at all. I am just getting blank values when I print.
int main(void)
{
char char_array[50];
char copied_array[50];
//int n = 2;
FILE* fpointer = fopen("hello_world.txt", "r");
FILE* fpointer2 = fopen("copyhello.txt", "w");
for(int i = 0;i < 50; i++)
{
fread(&char_array, sizeof(char), 1, fpointer);
copied_array[i] = char_array[i];
}
for(int j = 0;j < 50; j++)
{
printf("char_array: %c\n", copied_array[j]);
}
fclose(fpointer);
fclose(fpointer2);
}

working code. hope this becomes clearer :)
Note you're using fread/fwrite - compare with fgets/fputs for strings.
#include "stdio.h"
#include "string.h"
#define BUFSIZE 50
// memory size 'plus one' to leave room for a string-terminating '\0'
#define BUFMEMSIZE (BUFSIZE+1)
const char *file1 = "hello_world.txt";
const char *file2 = "copyhello.txt";
int main(void)
{
char char_array[BUFMEMSIZE];
char copied_array[BUFMEMSIZE];
FILE *fInput, *fOutput;
fInput = fopen(file1, "r");
if(fInput != NULL)
{
fOutput = fopen(file2, "w");
if(fOutput != NULL)
{
// make sure memory is wiped before use
memset(char_array, 0, BUFMEMSIZE);
memset(copied_array, 0, BUFMEMSIZE);
size_t lastSuccessfulRead = 0;
// the read-then-loop pattern: try and read 50 chars
size_t bytesRead = fread(char_array, sizeof(char), BUFSIZE, fInput);
while(bytesRead != 0)
{
// we got at least 1 char ..
// (to be used at end - so we know where in char_array is the last byte read)
lastSuccessfulRead = bytesRead;
// 'bytesRead' bytes were read : copy to other array
strncpy(copied_array, char_array, bytesRead);
// write to output file, number of bytes read
fwrite(copied_array, sizeof(char), bytesRead, fOutput);
// read more, and loop, see if we got any more chars
bytesRead = fread(char_array, sizeof(char), BUFSIZE, fInput);
}
// set char after the last-read-in char to null, as a string-terminator.
char_array[lastSuccessfulRead] = '\0';
// an array of chars is also a 'string'
printf("char_array: %s\n", char_array);
fclose(fOutput);
}
else printf("cant open %s\n", file2);
fclose(fInput);
}
else printf("cant open %s\n", file1);
}

Related

How come my fread returns an empty string?

When I write my string to file, I first write the length of the string as an int, followed by the string itself. Here is my code:
int wordLength = strlen(words);
fwrite(&wordLength,sizeof(int),1, outputFile);
fwrite(&words,sizeof(char),strlen(words), outputFile);
However, when I fread it back, I get an empty string. Here is my reading code:
int strLength;
fread(&strLength, sizeof(int), 1, f);
char* word = (char*) malloc(strLength*sizeof(char));
fread(&word, sizeof(char), strLength, f);
Why is this happening?
when I fread it back, I get an empty string. Here is my reading code:
Why is this happening?
fread(&strLength, sizeof(int), 1, f);
char* word = (char*) malloc(strLength*sizeof(char));
fread(&word, sizeof(char), strLength, f);
Code allocates insufficient memory. strLength*sizeof(char) is enough for the text yet not the terminating null character to make a string.
// char* word = (char*) malloc(strLength*sizeof(char));
char* word = malloc(strLength + 1u); // add 1
fread(&word, ...); is attempting to read data into the address of word, rather than into the memory just allocated.
// fread(&word, sizeof(char), strLength, f);
fread(word, sizeof *word, strLength, f); // drop &
The null character is never appended.
size_t count = fread(word, sizeof *word, strLength, f);
if (count != strLength) puts("Error");
else {
word[strLength] = '\0';
puts(word);
}
Notes:
Better to use size_t wordLength
Checking the return value of malloc() makes for good code.
size_t wordLength = strlen(words);
...
char* word = malloc(strLength + 1);
if (word == NULL) Hanlde_OutOfMemory();
Post does not show file open/closing details. Code may need to rewind(f) before reading data written.
This works on Ubuntu:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv)
{
FILE *outputFile;
FILE *inputFile;
char words[] = "This is a series of words";
int wordLength = strlen(words);
outputFile = fopen("outputFile", "w");
if ( outputFile == NULL )
{
perror("fopen failed: ");
exit(1);
}
fwrite(&wordLength,sizeof(int),1, outputFile);
fwrite(words,sizeof(char),strlen(words), outputFile);
fclose(outputFile);
inputFile = fopen("outputFile", "r");
if ( inputFile == NULL )
{
perror("fopen(2) failed: ");
exit(1);
}
int strLength = -99;
fread(&strLength, sizeof(int), 1, inputFile);
char* buff = (char*) malloc(strLength*sizeof(char));
fread(buff, sizeof(char), strLength, inputFile);
buff[strLength] = 0x00;
printf("Input Str: -->%s<--\n", buff);
}

Reading from file fails

I am reading a string from a file. After like the second or third time the function gets executed, one or more random characters become appended to the buffer string and I have no idea why that happens.
Here's the piece of code:
scorefile = fopen("highscore.dat", "rb");
if (scorefile)
{
fseek(scorefile, 0, SEEK_END);
length = ftell(scorefile);
fseek(scorefile, 0, SEEK_SET);
buffer = malloc(length);
if (buffer)
{
fread(buffer, 1, length, scorefile);
}
fclose(scorefile);
}
Am I doing something wrong here?
Let's spell it all out and go slightly more robust:
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
char *loadScoreFile(const char *filename)
{
char *buffer = NULL;
FILE *scorefile = fopen(filename, "r");
if (scorefile != NULL)
{
(void) fseek(scorefile, 0, SEEK_END);
int length = ftell(scorefile);
(void) fseek(scorefile, 0, SEEK_SET);
buffer = malloc(length + 1);
if (buffer != NULL)
{
assert(length == fread(buffer, 1, length, scorefile));
buffer[length] = '\0';
}
(void) fclose(scorefile);
}
return buffer;
}
int main()
{
for (int i = 0; i < 10; i++)
{
char *pointer = loadScoreFile("highscore.dat");
if (pointer != NULL)
{
printf("%s", pointer);
free(pointer);
}
}
return 0;
}
if you use buffer = malloc(length);, and then read length bytes into it, it will be one byte too short. Char arrays in C are zero-terminated, so they need an extra byte to but that zero. buffer = malloc(length+1); will fix this.

i am trying to read the values stored inside the buffer but instead its showing me the address?

i want to print the values in the location not the address..
when i run the program using breakpoint it does increases the values but doesn't print the values contained in the addresses..
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "conio.h"
int main()
{
char ch;
char buffer[100];
char* p;
p = buffer;
FILE *fp;
fp = fopen("D:\\Telenor_Short_01.vts","rb");// binary mode
fseek(fp,0,SEEK_END); //sets the file position of the stream to the given offset
int size=ftell(fp); //returns the current file position of the given stream.
printf("size of file is :%d\n",size);
if( fp == NULL ) //error checking
{
perror("Error while opening the file.\n");
exit(EXIT_FAILURE);
}
fread(p,1,100,fp);
for (int i=0;i<100;i++)
{
printf("%04x\n",*p);
p++;
}
fclose(fp);
/*printf("The contents of %s file are :\n", file_name);*/
/*int i;
while( ( ch = fgetc(fp) ) != EOF )
{
printf("%02X ",ch);
if( !(++i % 16) ) putc('\n', stdout);
}
fclose(fp);
putc('\n', stdout);*/
_getch();
return 0;
}
this is the output:
size of file is :185153907
5bf894
5bf895
5bf896
5bf897
5bf898
5bf899
5bf89a
5bf89b
5bf89c
5bf89d
5bf89e
5bf89f
5bf8a0
5bf8a1
5bf8a2
5bf8a3
5bf8a4
5bf8a5
5bf8a6
5bf8a7
5bf8a8
5bf8a9
5bf8aa
5bf8ab
5bf8ac
5bf8ad
5bf8ae
5bf8af
5bf8b0
5bf8b1
5bf8b2
5bf8b3
5bf8b4
5bf8b5
5bf8b6
5bf8b7
5bf8b8
5bf8b9
5bf8ba
5bf8bb
5bf8bc
5bf8bd
5bf8be
5bf8bf
5bf8c0
5bf8c1
5bf8c2
5bf8c3
5bf8c4
5bf8c5
5bf8c6
5bf8c7
5bf8c8
5bf8c9
5bf8ca
5bf8cb
5bf8cc
5bf8cd
5bf8ce
5bf8cf
5bf8d0
5bf8d1
5bf8d2
5bf8d3
5bf8d4
5bf8d5
5bf8d6
5bf8d7
5bf8d8
5bf8d9
5bf8da
5bf8db
5bf8dc
5bf8dd
5bf8de
5bf8df
5bf8e0
5bf8e1
5bf8e2
5bf8e3
5bf8e4
5bf8e5
5bf8e6
5bf8e7
5bf8e8
5bf8e9
5bf8ea
5bf8eb
5bf8ec
5bf8ed
5bf8ee
5bf8ef
5bf8f0
5bf8f1
5bf8f2
5bf8f3
5bf8f4
5bf8f5
5bf8f6
5bf8f7
but i want the values ..
First, check fp for NULL immediately after fopen. Second seek to the beginning of the file before fread. Last, most importantly, check the return value of fread, because that's the number of elements that was read into the buffer. It may be smaller than the buffer.
fp = fopen("D:\\Telenor_Short_01.vts","rb");// binary mode
if( fp == NULL ) //error checking
{
perror("Error while opening the file.\n");
exit(EXIT_FAILURE);
}
fseek(fp,0,SEEK_END); //sets the file position of the stream to the given offset
int size=ftell(fp); //returns the current file position of the given stream.
printf("size of file is :%d\n",size);
fseek(fp, 0, SEEK_SET);
int nread = fread(p, 1, 100, fp);
for (int i=0; i<nread; i++)
{
printf("%04x\n", *p);
p++;
}
fclose(fp);
In addition, in C, you can access array elements either by subscription or by pointers arithmetic, the two are the same effect:
char arr[8];
arr[3] is same as *(arr + 3);
&arr[3] is same as arr + 3;
To read the big file by chunks:
fseek(fp, 0, SEEK_SET);
char buf[4096];
int nread;
int i;
while (1) {
nread = fread(buf, 1, 4096, fp);
for (i=0; i<nread; i++)
{
printf("%02x\n", buf[i]);
}
if (nread < 4096)
break;
}
fclose(fp);

Why won't this work ? Dynamic memory beginner program

int main()
{
//FILE *out = fopen("keimeno.txt", "w+");
FILE *in = fopen("keimeno.txt", "r");
int fullbufflen=0 , i;
char buffer[100];
fgets(buffer, 100, in);
int bufflen = strlen(buffer);
char *text;
text =calloc(bufflen,sizeof(char));
char *strcat(text, buffer);
// printf("line of \"keimeno.txt\": %s", buffer);
// printf("size of line \"keimeno.txt\": %i\n\n", bufflen);
fullbufflen = bufflen;
while(fgets(buffer, 100, in)!=NULL)
{
// printf("line of \"keimeno.txt\": %s", buffer);
// printf("size of line \"keimeno.txt\": %i\n\n", bufflen);
text =realloc(text,bufflen*sizeof(char));
char *strcat(text, buffer);
fullbufflen = bufflen + fullbufflen ;
}
for (i = 0;i<fullbufflen;i++)
{
printf("%c\n",text[i]);
}
}
I am trying to copy the full text file (keimeno.txt) into a dynamic memory array, with a buffer of 100 character at most everytime. To test it at the end i tried to prinf the results. And i just cant get it to work. Dont know if there is a problem on the printf at the end, or the whole program is just wrong.
Also the dynamic array is supposed to have 0 size at the beggining, so if someone could tell me how to do that too, it would be welcome.
Thanks in advance.
There are a few issues:
char *strcat(text, buffer);
This is not how you call a function. This is a function declaration, and an incorrect one at that since it doesn't define the types of the arguments.
To call strcat, just do this:
strcat(text, buffer);
Next, you're not allocating enough space for your buffers:
text =calloc(bufflen,sizeof(char));
You need to add space for the null bytes that terminates the string:
text =calloc(bufflen + 1,sizeof(char));
Similarly here:
text =realloc(text,bufflen*sizeof(char));
This only reallocates a total of bufflen bytes. It does not add bufflen bytes to what was already allocated, and bufflen is unchanged from when it was first set outside of the while loop. Do this instead:
bufflen = strlen(buffer);
text =realloc(text,bufflen+fullbufflen+1);
This gives you enough space for the current length, the additional buffer, and the null byte.
Finally, make sure you fclose(in) and free(text) at the end to clean up your resources, and be sure to check the return value of fopen to ensure that the file opened successfully, and realloc/calloc to ensure that your allocations worked.
After the above changes, you code should look like this:
int main(void)
{
//FILE *out = fopen("keimeno.txt", "w+");
FILE *in = fopen("keimeno.txt", "r");
if (in == NULL) {
perror("open failed");
exit(1);
}
int fullbufflen=0 , i;
char buffer[100];
fgets(buffer, 100, in);
int bufflen = strlen(buffer);
char *text;
text =calloc(bufflen+1,sizeof(char));
if (text == NULL) {
perror("calloc failed");
exit(1);
}
strcat(text, buffer);
// printf("line of \"keimeno.txt\": %s", buffer);
// printf("size of line \"keimeno.txt\": %i\n\n", bufflen);
fullbufflen = bufflen;
while(fgets(buffer, 100, in)!=NULL)
{
// printf("line of \"keimeno.txt\": %s", buffer);
// printf("size of line \"keimeno.txt\": %i\n\n", bufflen);
bufflen = strlen(buffer);
text =realloc(text,bufflen+fullbufflen+1);
if (text == NULL) {
perror("realloc failed");
exit(1);
}
strcat(text, buffer);
fullbufflen = bufflen + fullbufflen ;
}
fclose(in);
for (i = 0;i<fullbufflen;i++)
{
printf("%c\n",text[i]);
}
free(text);
}
Here is one possible solution:
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#define ERR (-1)
#define GROW 100
static void die ( const char * msg ) { perror(msg); exit(1); }
int main ( void ) {
char * filename = "in.txt";
size_t buffSize = 0;
size_t buffUsed = 0;
ssize_t bytesRead = 0;
char * buffer = NULL;
char * tmp;
int fd;
fd = open(filename, O_RDONLY, 0);
if (fd == ERR) die("open");
do {
buffUsed += (size_t)bytesRead;
if (buffUsed == buffSize) {
tmp = realloc(buffer, buffSize += GROW);
if (tmp == NULL) die("realloc");
buffer = tmp;
}
bytesRead = read(fd, buffer + buffUsed, buffSize - buffUsed);
if (bytesRead == ERR) die("read");
} while (bytesRead > 0);
if (write(STDOUT_FILENO, buffer, buffUsed) == ERR) die("write");
free(buffer);
if (close(fd) == ERR) die("close");
return 0;
}
Like the original, the input filename is hard-coded which sub-optimal...

How to make a char array from a file?

#include <stdio.h>
#include <stdlib.h>
int count_arr(FILE *file)
{
int c,count=0;
//FILE *file;
//file = fopen("test.txt", "r");
if (file) {
while ((c = getc(file)) != EOF){
putchar(c);
++count;}
fclose(file);
}
return count;
}
void make_arr (FILE *file, char arr[]){
int c,n=0,count=0;
char ch;
//FILE *file;
//file = fopen("test.txt", "r");
if (file) {
while ((c = getc(file)) != EOF){
ch = (char)c;
arr[n]=ch;
++n; }
fclose(file);
}
}
int main(){
FILE *file;
int n;
//scanf("%c",&file_name);
file = fopen("test.txt","r");
int count = count_arr(file);
char arr [count];
make_arr(file, arr);
for(n=0; n<count;++n) printf("%c",arr[n]);
}
So far this is all I have for my code. I know I am doing it completely wrong. When I print out the char array it prints random junk... I am trying to code a function "make_arr" that passes an array which gets stored with characters from a file. Any help would be appreciated!
Here is an small example that reads a file into a buffer:
FILE* file = fopen("file.txt", "r");
// get filesize
fseek(file, 0, SEEK_END);
int fsize = ftell(file);
fseek(file, 0, SEEK_SET);
// allocate buffer **note** that if you like
// to use the buffer as a c-string then you must also
// allocate space for the terminating null character
char* buffer = malloc(fsize);
// read the file into buffer
fread(buffer, fsize, 1, file);
// close the file
fclose(file);
// output data here
for(int i = 0; i < fsize; i++) {
printf("%c", buffer[i]);
}
// free your buffer
free(buffer);
If you really would like to use a function to fill your buffer this would work (not really see the point though), although I still will make only one read operation:
void make_array(FILE* file, char* array, int size) {
// read entire file into array
fread(array, size, 1, file);
}
int main(int argc,char** argv) {
// open file and get file size by first
// moving the filepointer to the end of the file
// and then using ftell() to tell its position ie the filesize
// then move the filepointer back to the beginning of the file
FILE* file = fopen("test.txt", "r");
fseek(file, 0, SEEK_END);
int fs = ftell(file);
fseek(file, 0, SEEK_SET);
char array[fs];
// fill array with content from file
make_array(file, array, fs);
// close file handle
fclose(file);
// output contents of array
for(int i = 0; i < fs; i++) {
printf("%c\n", array[i]);
}
return 0;
}
Like I stated in the comments above you need to add space for the terminating null character if you like to use the char array as a string:
char* array = malloc(fs + 1);
fread(array, fs, 1, file);
// add terminating null character
array[fs] = '\0';
// print the string
printf("%s\n", array);

Resources