簡體   English   中英

在C中逐行讀取文件(不使用fgets)

[英]read file line by line in C(without using fgets)

我有一個包含3行的文件,我正在嘗試讀取此文件並將每行保存為單獨的字符串。 這是我嘗試執行的操作,它確實保存了第一行,但通過保存第一行和第二行覆蓋了它,並且我無法理解如何將每一行保存為單獨的字符串,並且我也遇到錯誤->

*檢測到堆棧粉碎* :/home/ubuntu/workspace/ex12.co已終止中止

 #include <stdio.h>
 #include <fcntl.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include<stdio.h> 
 #include<fcntl.h> 
 #include<errno.h> 
 #include <unistd.h>
 extern int errno;                               
int main( int argc, char *argv[] )  {
    char *path1;   
    char  firstline[80];
    char  secondline[80];
    char  thirdline[80];  

    printf("Program name %s\n", argv[0]);

    if( argc == 2 ) {
         printf("The path of the config file that you supplied is %s\n", argv[1]);
    }
    else if( argc > 2 ) {
        printf("Too many arguments supplied.\n");
    }
    else {
        printf("One argument expected.\n");
    }

    int fd1 = open(argv[1], O_RDONLY | O_CREAT);  

    if (fd1 ==-1) 
    { 
        // print which type of error have in a code 
        printf("Error Number % d\n", errno);  

        // print program detail "Success or failure" 
        perror("Program"); 
        exit(EXIT_FAILURE);
    }       
    else {            
        char c;
        int i=0;            

        while ((read(fd1, &c, 1) == 1) )
        {                
            firstline[i++]=c;                
            if(c=='\n')
            {
                //printf("end of line"); 
                printf("%s",firstline);
            }

        }
    }
    int close(int fd1);         
    return 0;        
}

注意:我不想使用fopen,fgets,sscanf或getline。 任何幫助,將不勝感激

printf打印,直到看到NULL終止符為止。 您的printf遍歷了未分配的內存區域,因為您沒有在字符串末尾插入NULL(值0)。 另外,您忘記了將i重新初始化為0。

while ((read(fd1, &c, 1) == 1) )
{                
    firstline[i++]=c;                
    if(c=='\n')
    {
        firstline[i] = 0;
        i = 0;
        //printf("end of line"); 
        printf("%s",firstline);
    }
}

你得到錯誤的原因很可能是因為你永遠不重置i回0,所以你保持閱讀超過80個字符firstline

至於將每一行保存到自己的字符串中,只需要使用其他變量,而不是一直使用firstline

有兩種方法可以做到這一點:

  1. 當您檢測到行尾時,請退出循環(帶有break ),然后開始另一個循環,在此循環中將字符放入secondline 第三相同。

  2. 如果您已經了解了一些有關指針的知識,則可以保留一個循環,但可以使用一個額外的變量,例如char *currentLine ,它將保存您要讀取的數組的地址。 每次您檢測到行尾時currentLine = secondline更改地址,如下所示: currentLine = secondline

還請記住,在讀取的每一行的末尾都應加上“ \\ 0”,否則當您嘗試將讀取的內容打印到屏幕上時,程序可能會打印垃圾。

以下建議的代碼:

  1. 干凈地編譯
  2. 執行所需的功能
  3. 適當檢查並處理錯誤
  4. 給出“魔術”數字(3、80)有意義的名稱

現在,建議的代碼為:

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>

#define MAX_LINES 3
#define MAX_LINE_LEN 80


int main( int argc, char *argv[] )  
{
    char Lines[ MAX_LINES ][ MAX_LINE_LEN ] = { '\0' };


    if( argc != 2 )
    {
        fprintf( stderr, "USAGE: %s <configFileName>\n", argv[0] );
        exit( EXIT_FAILURE );
    }

    // implied else, correct number of command line arguments


    int fd1 = open(argv[1], O_RDONLY );  

    if (fd1 ==-1) 
    { 
        perror( "open failed" ); 
        exit(EXIT_FAILURE);
    }  

    // implied else, open successful        

    char c;

    for( int i = 0; i < MAX_LINES; i++ )
    {
        for( int j=0; j< MAX_LINE_LEN; j++ )
        {
            ssize_t bytecount = read(fd1, &c, 1 );
            if( bytecount < 0 )
            {
                perror( "read failed" );
                close( fd1 );
                exit( EXIT_FAILURE );
            }

            // implied else, read successful 

            Lines[ i ][ j ] = c;

            if( c == '\n' )
            {
                break;
            }   
        } 
    }

    for( int i = 0; i< MAX_LINES; i++ )
    {
        printf( "%s\n", Lines[i] );
    }

    close( fd1 );         
    return 0;        
}

注意:此代碼假定每行少於80個字符

針對自己的源文件運行建議的代碼將導致:

#include <stdio.h>

#include <stdlib.h>

#include <sys/types.h>

這是一個示例,演示您的示例從第一個循環開始的制動:

#define MAXLENGTH 80    
...

char  firstline[MAXLENGTH + 1] = {0};
char  secondline[MAXLENGTH + 1] = {0};
char  thirdline[MAXLENGTH + 1] = {0};  
....
else {            
    char c;
    int i=0;            
    while ((read(fd1, &c, 1) == 1 && i < MAXLENGTH)
    {                
        firstline[i++]=c;                
        if(c=='\n')
        {
            break; /* break from first loop */
        }
    }
    /* add a '\0' to the end of the string! */
    firstline[i] = '\0';
    //printf("end of line"); 
    printf("%s",firstline);
    i=0;            
    while ((read(fd1, &c, 1) == 1 && i < MAXLENGTH)
    {                
        secondline[i++]=c;                
        if(c=='\n')
        {
            break; /* break from second loop */
        }
    }
    /* add a '\0' to the end of the string! */
    secondline[i] = '\0';
    printf("%s",secondline);
    i = 0;
    int i=0;            
    while ((read(fd1, &c, 1) == 1 && i < MAXLENGTH)
    {                
        thirdline[i++]=c;                
        if(c=='\n')
        {
            break; /* break from third loop */
        }
    }
    /* add a '\0' to the end of the string! */
    thirdline[i] = '\0';
    //printf("end of line"); 
    printf("%s",thirdline);
}
...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM