Reputation: 1786
I have a problem with reading a file in C.
I want to read a file line by line.
Each line contains 25 characters and each character has a special value that I have to use in other functions. My code:
int read_file(const char* filename){
FILE* file = fopen(filename, "r");
char line[25];
int i;
int counter = 0;
while (fgets(line, sizeof(line), file))
{
if (counter == 0)
{
counter++;
}
else
{
for(i = 0; i < 25 ; i++){
printf("%s",line[i]);
}
}
}
fclose(file);
return 0;
}
I have to do something else then print it, but when I try this code, it gives errors, so doing something else would do the same I guess. So my code needs to read the file line by line and then I need to be able to read it character by character.
Upvotes: 0
Views: 7766
Reputation: 16607
printf("%s",line[i]); // %s expects char * and line[i] is a char
This should be -
printf("%c",line[i]); // to print character by charcter
To store 25
characters declare line
as -
char line[25+1]; // +1 for null character
Note - As you ask in comment to %s
can be used as -
printf("%s",line); // no loop required
Upvotes: 1
Reputation: 75062
%c
have to be used to print one character via printf
.fixed code:
#include <stdio.h>
int read_file(const char* filename){
FILE* file = fopen(filename, "r");
char line[27]; /* an array of 25 elements isn't enough to store lines of 25 characters: +1 for newline and +1 for terminating null character */
int i;
int counter = 0;
if (file == NULL) return 1; /* check if the file is successfully opened */
while (fgets(line, sizeof(line), file))
{
if (counter == 0)
{
counter++;
}
else
{
for(i = 0; i < 25 ; i++){
printf("%c",line[i]); /* use %c instead of %s to print one character */
}
}
}
fclose(file);
return 0;
}
Upvotes: 2