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

Yes a code snippet would be helpful, lets start by seeing yours.

@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.

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';
										      }
	}
}

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

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.

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.

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

To find the size of file -
open file
fseek to end
ftell will give you the size.

@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)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.