0

Hi...
i have A File And I Want to read the file and store all of its data in a single file what should i do...
Please help....
A C Code Snippet would be very helpful

6
Contributors
9
Replies
12
Views
5 Years
Discussion Span
Last Post by abhimanipal
0

@OP

Do you mean you want to read a file into a char array? That is what your title suggests. Is there a typo error?

while (not_end_of_file) {
    read character into array
}

You can use fgetc() (other ways possible too) to read a character from the file.


PS: i agree with gerard4143. there are lots of resources on files that you can go through.

Edited by myk45: n/a

0

Hello All...
Ya Myk is crrct
thats what i mean..
Reading all the data in a file and storing it in a single char array...
The Problem with my C Code Snippet is that it is having too many calls to the function realloc..
Can You Suggest an Efficient way without the use of realloc..?

int str_cat_len(char*s1,char*s2)
{
	int n1 = strlen(s1);
	int n2 = strlen(s2);
	return((n1+n2));
}

int main()
{
	char A[100];
	char *A_s=NULL,;
	char *tmp=NULL;
	FILE *A_f,*B_f;
	size_t lsize = 0;
	char* line = NULL;
	A_s = (char *)malloc(1*sizeof(char));
	A_s[0]='\0';
	printf("Enter The Full Path Of the file:\t");
	gets(A);
	if((A_f  = fopen(A,"r"))==NULL)
	{
		printf("File not Available");
		exit(0);
	}
	else
	{
		while (getline(&line, &lsize, A_f) != -1) {
			n = str_cat_len(line,A_s);
			A_s = (char *)realloc(A_s,sizeof(char)*(n+1));
		      strcat(A_s,line);
			A_s[n]='\0';
										      }
	}
}

Edited by WaltP: Added CODE Tags -- please use them.

0

Well, yeah, why would you want to realloc() one character at a time? Add 512 bytes at a time.

0

I Am Not reaalocing 1 character at a tym Walt...
I am reallocing a whole line of the text file at a time...
and dats the problem i dont wanna use realloc at all...
help me out.

0

Then find out how big the files is first. Read through the file once so you know how big it is. Then malloc() the buffer and read the file in one read.

Use the read() function to make it faster.

Edited by WaltP: n/a

0

But the time complexity would increase drastically for files with large size then...
What About that..??

0

@rohan
I think, theoretically speaking the approach described by Walt is faster than your approach

Walt's Approach
Read the entire file to find the size of the file --> O(n)
Alloc a buffer of size n and copy the contents of the file in buffer --> O(n)
O(n) + O(n) = O(n)

Your approach

while(contents of file exist)
{
         Read 1 line of file --> O(1)   Say
         Copy the contents of the buffer into new buffer ---> O(n)
}

This means theoretical complexity of O(n)*O(n) = O(n^2)

Edited by Nick Evan: Fixed formatting

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.