'fscanf' does not change pointers but it can corrupt memory if you do not allocate enough space for your input.
And you are not allocating the memory correctly: string1
and string2
are pointers, so all you are allocating is a size of a pointer (4 or 8 bytes depending on your system).
If you need to read a line from a file and you do not know the maximum length of the line in advance, you can not use fscanf
.
You need to allocate a starting buffer, say something like:
string1 = malloc(512 * sizeof(char));
Were 512 is an arbitrary but reasonably large length for a line.
You then use fread
to read one byte at a time in a loop, and check for end of line (usually '
').
You must also count how much you read, and if the line is longer than 512 bytes, use realloc
to increase the size of your buffer, like so:
if (bytesRead == (string1Size - 1) && curByte != '
') {
string1Size += 512;
string1 = realloc(string1, string1Size);
}
Here, bytesRead
is an int
variable counting how many bytes you successfully read so far, and string1Size
is also int
variable used to track the size of string1
buffer.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…