假设我有一个包含以下内容的文件:
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);
}
}
}
如何让它只保存变量 line
中每行的前 75 个字符?
上面的代码给出了以下输出:
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;
}
关于c - 在 C 中给定一个文件名,如何读取每行只有 75 个字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58497508/