c - 在 C 中使用 fscanf 读取另一行

标签 c file-io scanf

假设我有一个文件要读取:

//it may contain more than 2 lines
12 6
abadafwg

假设现在我已经阅读了这样的第一行:

char input[999];
while(!feof(fpin))
{
    fscanf(fpin, " %[^\n]", input);
    //do something here with these numbers
    //should do something here to read 2nd line
}

这是我的问题,如何读取该文件的第二行? 请帮忙QAQ

最佳答案

建议不要使用 fscanf(fpin, "%[^\n]", input),而是使用 fgets(),因为这样可以防止缓冲区溢出。您可以将其用于这两行,然后根据需要进行解析。

if (fgets(input, sizeof(input), fpin) == 0) {
  // handle error, EOF
}
int i[2];
int result = sscanf(input,"%d %d", &i[0], &i[1]);
switch (result) {
  case -1: // eof
  case 0: // missing data
  case 1: // missing data
  case 2: // expected
}
if (fgets(input, sizeof(input), fpin) == 0) {
  // handle error, EOF
}
// use the 'abadfwg just read

关于c - 在 C 中使用 fscanf 读取另一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17287916/

相关文章:

c - `scanf("%*[^\n]%*c")` 是什么意思?

c - 为什么取消引用 C 中的引用?在 * 旁边使用 &

使用字符串检查宏定义

java - 在保存到文件之前将大量定期获取的文本存储到缓存中是个好主意吗?

c# - 无法删除 Windows 应用商店应用程序中的文件 - 访问被拒绝。 (HRESULT : 0x80070005 (E_ACCESSDENIED))

android - 读取 Android 原始文本文件

c - fork() 的执行顺序?

c - PIC12F675设置定时器功能。它到底是做什么的

c - C 守护进程中的运行时信息

c - 从http套接字中提取位置