I'm trying to loop over each character of a line within fgets, but I am running into errors, as I'll explain below.
int main(int argc, char* argv[]) {
char arr[200]
int currS = sizeof(arr) / sizeof(char);
// call readIt function
}
void readIt(char* argv[], char arr[], int currS) {
FILE* file;
file = NULL;
file = fopen(argv[1], "r");
while(fgets(arr, currS, file) != NULL)
for (int i = 0; i < sizeof(arr); i++)
print each char of current line
}
When I do the for loop over each line, each line output will be the length of the very FIRST line in the file. The # of times the for loop iterates never changes. How do I update it? I looked at other SO questions but they aren't very helpful..
In the readIt()
function, you need strlen(arr)
, not sizeof arr
. The latter will give you the size of a char *
, which is always the same, regardless of the length of the string to which it might point.
You should also check that the return from fopen()
is not NULL
, since fopen()
can fail for many reasons.
void readIt(char* argv[], char arr[], int currS) {
FILE * file = fopen(argv[1], "r");
if ( file ) {
while( fgets(arr, currS, file) ) {
const int len = strlen(arr);
for ( int i = 0; i < len; ++i ) {
// print each char of current line
}
}
}
}
Note that using the variable len
here means you only calculate the length of the string once, before you start to loop over it, rather than calculating it every time through the loop which would happen if you did for ( int i = 0; i < strlen(arr); ++i )
. If all you're doing is printing every character, then the length of the string isn't going to change in between calls to fgets()
, so it's inefficient to calculate it more than once.
Also, unless for some reason you want the array in main()
to contain the last line read from the file after readIt()
returns, you could more easily define arr
within readIt()
itself, to avoid the need to pass it to that function at all, for instance:
void readIt(char* argv[]) {
FILE * file = fopen(argv[1], "r");
if ( file ) {
char arr[200];
while( fgets(arr, sizeof arr, file) ) {
const int len = strlen(arr);
for ( int i = 0; i < len; ++i ) {
// print each char of current line
}
}
}
}
Because arr
is now an actual array within readIt()
, rather than a pointer to char
(you can't pass an array to a function, only the address of one), sizeof arr
will give you the actual size of the array, rather than the size of a char *
, so you can pass that to fgets()
.