zoukankan      html  css  js  c++  java
  • C语言按行读入文件

    getline() 函数无论一行多长,动态分配内存读入行

     1 #include <stdio.h>
     2 #include <stdlib.h>
     3 #include <string.h>
     4 
     5 int main(int argc,const char *argv[])
     6 {
     7     FILE *fp;
     8     size_t len = 0;
     9     char *str = NULL;
    10     ssize_t read;
    11     
    12     if(argc != 2)
    13     {
    14         fprintf(stderr,"usage: %s <src>
    ",argv[0]);
    15         exit(1);
    16     }
    17 
    18     if((fp=fopen(argv[1],"r")) == NULL)
    19     {
    20         perror("fopen()");
    21         exit(1);
    22     }
    23     
    24     while((read = getline(&str,&len,fp)) != -1)
    25     {
    26         
    27         //str[read-1]=''; 去掉行末换行符
    28         fprintf(stdout,"%s",str);
    29     }
    30     fclose(fp);
    31 
    32     exit(0);
    33 }
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.
  • 相关阅读:
    Codeforces 798C
    Codeforces 798B
    Codeforces 798A
    HDU
    HDU
    HDU
    加速cin的技巧
    Codeforces Gym
    Codeforces Gym
    Solutions to an Equation LightOJ
  • 原文地址:https://www.cnblogs.com/mmtinfo/p/13036039.html
Copyright © 2011-2022 走看看