[英]Reading file, line by line, character by character in C
我在使用C读取文件时遇到问题。
我想逐行读取文件。
每行包含25个字符,每个字符都有一个特殊的值,我必须在其他函数中使用该值。 我的代码:
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;
}
我必须做些其他的事情然后打印它,但是当我尝试这段代码时,它会出错,所以我猜想做其他的事情也可以做到。 因此,我的代码需要逐行读取文件,然后才能逐字符读取文件。
%c
通过printf
打印一个字符。 固定代码:
#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;
}
printf("%s",line[i]); // %s expects char * and line[i] is a char
这应该是-
printf("%c",line[i]); // to print character by charcter
要存储25
字符,请将line
声明为-
char line[25+1]; // +1 for null character
注意 -如您对%s
评论中所述,可以用作-
printf("%s",line); // no loop required
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.