Reputation:
I have written a piece of code which reads a text file foo.txt which is of format:
1
2
3
4
It stores the last number and increments it and writes it back. This is the part where I'm storing the last number and the next part of the code will be writing the number to the file. The file is called by ./readfile 100 foo.txt
, where 100 is the number of times it has to increment the last number.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
FILE *fp;
char ch[100];
int i = 0;
int j = 0;
int count = atoi(argv[1]);
while (count != 0) {
fp = fopen(argv[2], "r");
while (fp) {
ch[i] = fgetc(fp);
i++;
j = i;
printf("%d", j);
}
fclose(fp);
count--;
}
return 0;
}
Upvotes: 0
Views: 69
Reputation: 139
After you fix "while (fp)" issue. You still has problem with ch[i]. With your code, "i" will be increased to 400. So segmentation fault occurs.
while(fp)
{
ch[i] = fgetc(fp);
i++;
j = i;
printf("%d", j);
}
Upvotes: 1
Reputation: 155373
Your problem is:
while (fp)
A FILE*
is, to a boolean test, just another pointer. So as long as it opened successfully, that test always passes. You keep reading character at a time, storing into successive elements of the array, until you overflow, and eventually end up writing into unallocated memory entirely (or coincidentally stomping something important and causing a crash some other way).
You really want something like:
// Must read into int; EOF itself is not a char value
int inchar;
// Read and test for EOF
while((inchar = fgetc(fp)) != EOF)
{
ch[i] = inchar; // Store
i++;
printf("%d", inchar); // Print raw value returned by fgetc
}
Upvotes: 1