c - 从文件中读取行直到换行并将其存储在字符数组中
问题描述
我正在尝试编写一个程序,该程序从文件中读取一行并将其存储到 char 数组中。由于我只想阅读一行,因此我希望它在换行处停止阅读。我当前的代码并没有完全达到我想要的效果。从包含以下内容的文件中:
Hello
u
我想存储Hello
在一个字符数组中。我当前的代码只存储llo
和其他一些垃圾。这是我到目前为止所拥有的:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char random[100];
FILE *fp;
fp = fopen("testing.txt", "r");
if(fp == NULL){
printf("Can't open the file\n");
exit(1);
}
char c;
while((c = fgetc(fp)) != EOF){
for(int i = 0; c != '\n'; i++){
fscanf(fp, "%c", &c);
random[i] = c;
}
}
printf("%s\n", random);
return 0;
}
解决方案
while((c = fgetc(fp)) != EOF){ <-- You consume a byte (H)
for(int i = 0; c != '\n'; i++){
fscanf(fp, "%c", &c); <-- You consume another byte (E) and overwrite c
random[i] = c; <-- You read c (H) gets loosed
}
}
并且您不检查缓冲区溢出,而是
char random[100] = ""; // Initialize, a string must be NUL terminated
int c, i = 0;
while (i < 99 && (c = fgetc(fp)) != EOF && c != '\n')
{
random[i++] = c;
}
或者更好的是,使用fgets
并去除尾随换行符
if (fgets(random, sizeof random, fp))
{
random[strcspn(random, "\n")] = '\0';
}
编辑:
想象一下文本文件的第一行有一个数字,第二行有一个单词......
在这种情况下,我将使用strtol
int number = 0;
// Line 1 - read the int
if (fgets(random, sizeof random, fp))
{
int number = (int)strtol(random, NULL, 10); // 10 means base 10 (decimal)
// As pointed out by @chux in comments, if the line contains
// more than 100 chars you end up reading garbage in the next
// call to fgets, sanitize the line:
if (strchr(random, '\n') == NULL)
{
int c;
while ((c = fgetc(fp)) != '\n' && c != EOF); // flush garbage
}
}
// Line 2 - read the string, you can reuse `random`:
if (fgets(random, sizeof random, fp))
{
random[strcspn(random, "\n")] = '\0';
}
printf("%d %s\n", number, random);
推荐阅读
- r - Caret 的 train.recipe 似乎没有应用配方程序来删除 NA,随后交叉验证失败
- html - 在 Flutter 中从网站发布用户名和密码
- python - 尝试单击 CheckBox 时出现“元素单击被拦截”错误
- java - 如何从 Java 文本文件中解析像“1.8400e-016”这样的数字?
- python - Pandas 指定 read_csv() 类型推理的优先顺序或列表
- powerquery - PowerQuery 填充缺失的日期和数据
- python - Win.blit 参数一个必须是表面而不是元组,但它是一个正在运行的精灵?
- c# - 为图像/x-xbitmap mime 类型正确的 ImageFormat
- android - 如何解决由 com.google.firebase:firebase-ml-vision:24.0.0 引起的重复类异常
- java - 为 neo4j-admin 导入设置堆内存