假设我有一个包含以下内容的文件:
This line contains more than 75 characters due to the fact that I have made it that long.
Testingstring1
testingstring2
这是我的代码:
void checkLine( char const fileName[]){
FILE *fp = fopen(fileName,"r");
char line[75];
while (1) {
fgets(line,75,fp);
if (feof(fp)){
break;
} else {
printf("%s\n", line);
}
}
}
如何使它仅将每行的前75个字符保存到变量line
中?
上面的代码提供以下输出:
This line contains more than 75 characters due to the fact that I have mad
e it that long.
Testingstring1
testingstring2
预期的输出应该是这样的:
This line contains more than 75 characters due to the fact that I have mad
Teststring1
Teststring2
最大strlen将为74。
bool prior_line_ended = true;
while (1) {
fgets(line, 75, fp);
if (feof(fp)){
break;
}
// Remove any line end:
char* pos = strchr(line, '\n');
//char* pos = strchr(line, '\r');
//if (pos == NULL) {
// pos = strchr(line, '\n');
//}
bool line_ended = pos != NULL;
if (line_ended) {
*pos = '\0';
}
// Output when starting fresh line:
if (prior_line_ended) {
printf("%s\n", line);
}
prior_line_ended = line_ended;
}
类似这样的东西:
// If we read an incomplete line
if(strlen(line) == 74 && line[73] != '\n') {
// Read until next newline
int ch; // Yes, should be int and not char
while((ch = fgetc(fp)) != EOF) {
if(ch == '\n')
break;
}
}
将其放在您的else块之后。
这里是正确修复打印输出的完整版本:
void checkLine( char const fileName[]){
FILE *fp = fopen(fileName,"r");
char line[75];
while (1) {
fgets(line,75,fp);
if (feof(fp)){
break;
} else {
// fgets stores the \n in the string unless ...
printf("%s", line);
}
if(strlen(line) == 74 && line[73] != '\n') {
// ... unless the string is too long
printf("\n");
int ch;
while((ch = fgetc(fp)) != EOF) {
if(ch == '\n')
break;
}
}
}
}
if(strlen(line) == 74 && line[73] != '\n')
可以用if(strchr(line, '\n'))
代替。
当然,在出现错误的情况下,您应该检查fgets
和fopen
的返回值。