c - 如何编写从文本文件返回特定行的 ANSI C 用户定义函数?

标签 c file-io

如何编写从文本文件返回特定行的 ANSI C 用户定义函数?

char * ReadFromFile(const char * fileName, int line)
{
    //..........
}

最佳答案

这应该可以解决问题:

char * ReadFromFile(const char * fileName, int line)
{

  FILE *fp;

  char c;
  char *buffer = malloc( 100 * sizeof(char) );  // change 100 to a suitable value; 
  int buffer_length = 100;                      // eg. max length of line in your file

  int num = 0;

  if(line < 0)   // check for negative  line numbers
  {
    printf("Line number must be 0 or above\n");
    return(NULL);
  }

  if( ( fp = fopen(fileName,"r") ) == NULL )
  {
     printf("File not found");
     return(NULL);
  }

  while(num < line)  // line numbers start from 0
  {
    c = getc(fp);
    if(c == '\n')
    num++;      
  }

  c = getc(fp);

  if(c == EOF)
  {
    printf("Line not found\n");
    fclose(fp);
    return(NULL);
  } 
  else
  {
    ungetc(c,fp);     //push the read character back onto the stream
    fgets(buffer,buffer_length,fp);
    fclose(fp);
    return(buffer);
  }

编辑 caflorenzog 在评论中建议的边界条件已包含在内。从来没有想过防错会如此乏味! (仍然不检查行号超过 int 可以安全容纳的情况。这留给 OP 练习 :)

关于c - 如何编写从文本文件返回特定行的 ANSI C 用户定义函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3816249/

相关文章:

C++读取缓冲区大小

java - 有没有一种简单的方法可以按扩展名类型查找文件并将它们放入 Java 中的 File 数组中?

c - 指针处的值仅在使用时才会更新

c - 非指针数组中的哨兵

c - 为什么我在文件开头有一个连字符?

c++ - 如何判断返回的指针是在栈上还是堆上

C99 VLA 大小确定和 sizeof 运算符

python - 快速写入状态文件

java - 读取多个文本文件,附加一些html标签,然后将其保存到用户在java中选择的目录

php - 为什么 move_uploaded_file 不起作用?