Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

URGENT, ARRARY and POINTER 1

Status
Not open for further replies.

ty1975

Programmer
Nov 5, 2002
12
GB
Hi there,

I have to read in a file line by line, and then write into another file. Since I do not know how many characters in one line, I can not define a char array with fixed size. so what shall I do then?

I did sth like
char *line;
char ch;

//read the line char by char
for (j = 0; ((ch = getc(out)) != EOF) && (ch != '\n'); j++)
line[j] = ch;

but when I run it , it always shows up "ACCESS VIOLATION". Please help
 
Use a buffer big enough for a line.
char line[256];
and use fgets to get the whole line
fgets(line,255,infile);
then use fputs to put your line to your output file
fputs(line,outfile);

Good luck
 
As a matter of interest in your original example you probably got your error becuase you were attempting to write to an area of memory you had not created!

char * line; defines a POINTER of type char, it does not allocate any memory and, in most systems, an uninitialised pointer contains NULL and therefore points to address 0. You program does not have write access to that area of memory - hence the error.

You need to do :

char * line;

if((line=malloc(number_of_bytes_required))==NULL)
return error;
.
.
use the area pointed to by line
.
.
free(line);

DucatiST2 is correct in that the method he proposes is the method used by the bulk of C programmers (especially now memory is cheap and plentiful) as you can afford to allocate a very large array for your buffer thus hopefully always having a buffer big enough to cater for any possible line.

In the old days if we did not know how big the line could be we would take the approach of malloc'ing an area of memory (say 100 bytes) then reading 100 bytes from the file into this area. If we had not yet got to the end of the first record then we would use realloc to increase the size of the area by another 100 bytes and read the next 100 bytes and repeat until we had the whole record. As we read the remainder of the records this area of memory would grow as longer records were encountered but would never be shrunk. This method is more inefficient than the method used now but did cater for unknown records lengths which the current method does not.

Cheers - Gavin
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top