C read file line by line

前端 未结 17 2180
后悔当初
后悔当初 2020-11-22 03:45

I wrote this function to read a line from a file:

const char *readLine(FILE *file) {

    if (file == NULL) {
        printf(\"Error: file pointer is null.\"         


        
17条回答
  •  别跟我提以往
    2020-11-22 04:10

    I want a code from ground 0 so i did this to read the content of dictionary's word line by line.

    char temp_str[20]; // you can change the buffer size according to your requirements And A single line's length in a File.

    Note I've initialized the buffer With Null character each time I read line.This function can be Automated But Since I need A proof of Concept and want to design a programme Byte By Byte

    #include
    
    int main()
    {
    int i;
    char temp_ch;
    FILE *fp=fopen("data.txt","r");
    while(temp_ch!=EOF)
    {
     i=0;
      char temp_str[20]={'\0','\0','\0','\0','\0','\0','\0','\0','\0','\0','\0','\0','\0','\0','\0','\0','\0','\0','\0'};
    while(temp_ch!='\n')
    {
      temp_ch=fgetc(fp);
      temp_str[i]=temp_ch;
      i++;
    }
    if(temp_ch=='\n')
    {
    temp_ch=fgetc(fp);
    temp_str[i]=temp_ch;
    }
    printf("%s",temp_str);
    }
    return 0;
    }
    

提交回复
热议问题