Подсчет строк файла с использованием файлового дескриптора в C - PullRequest
0 голосов
/ 17 января 2019

Я пытаюсь подсчитать количество строк файла, который я читаю через дескриптор файла, но я не знаю, что я делаю неправильно, потому что это не работает.

Это код:

fd_openedFile = open(filename, O_RDONLY)        
char *miniBuffer[1];
int lineCounter = 0;
while( read(fd_openedFile, miniBuffer, 1) >0) {
    if (*miniBuffer[0] == '\n')
        lineCounter++;
}

Программное обеспечение никогда не входит в «если», и я протестировал множество вариантов, которые, как мне показалось, могли бы работать, но ни один из них не работал (это только тот, который имеет больше смысла для меня).

Любая помощь будет высоко оценена.

Большое спасибо!

Я добавил полный код ниже:

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

void err_sys(const char* cadena, int continueExecuting) {
    perror(cadena);
    if (continueExecuting == 0)
        exit(1);
}

int main()
{
    //vars
    char filename[200];
    int fd_output = 1;
    int fd_openedFile = -1;
    int fd_newFile = -1;


    //Ask for the file and open it
    while (fd_openedFile < 0){
        write(fd_output, "Write the filename: ", 20);
        scanf("%s", filename);
        if ((fd_openedFile = open(filename, O_RDONLY)) < 0)
            err_sys("Error opening the original file", 1);
    }

    //Construct the new file's name
    char *partOfOldFilename = strtok(filename, ".");
    char newFileName[208], finalPart[8];
    strcpy(newFileName,  partOfOldFilename);
    strcpy(finalPart, "OUT.txt");
    strcat(newFileName, finalPart);

    //Create the new file
    if ((fd_newFile = open(newFileName, O_WRONLY | O_CREAT)) < 0)
        err_sys("Error opening the new file", 1);

    //Count the number of lines
    char miniBuffer[1];
    int lineCounter = 0;
    while( read(fd_openedFile, &miniBuffer[0], 1) >0) {
        write(fd_output, "R", 1); //To debug
        if (miniBuffer[0] == '\n') {
            lineCounter++;
            write(fd_output, "1", 1); //To debug
        } else {
            write(fd_output, "0", 1); //To debug
            write(fd_output, miniBuffer, 1); //To debug
        }
    }

    lseek(fd_openedFile,0,SEEK_SET);
    write(fd_output, "=========\n", 10); //To debug


    //Count the number of chars per line
    char* charsPerLine[lineCounter];
    lineCounter = 0;
    int charCounter = 0;
    while( read(fd_openedFile, miniBuffer, 1) >0){
        write(fd_output, "C", 1); //To debug
        if (miniBuffer[0] == '\n') {
            *(charsPerLine[lineCounter]) = charCounter +'0';
            lineCounter++;
            charCounter = 0;
            write(fd_output, "1", 1); //To debug
        } else {
            write(fd_output, "0", 1); //To debug
            write(fd_output, miniBuffer, 1); //To debug
            charCounter ++;
        }
    }
    lseek(fd_openedFile,0,SEEK_SET);
    write(fd_output, "END", 4); //To debug

    //Write a copy of the original file starting each line with the number of chars in it
    lineCounter = 0;
    int bufSize = 1;
    char buffer[bufSize];
    //First number write
    if (write(fd_newFile,charsPerLine[lineCounter], bufSize)!=bufSize)
        err_sys("write_error", 0);
    lineCounter++;
    while( read(fd_openedFile, buffer, bufSize) >0){
        if (write(fd_newFile,buffer, bufSize)!=bufSize)
            err_sys("write_error", 0);
        if (buffer[0] == '\n') {
            if (write(fd_newFile,charsPerLine[lineCounter], bufSize)!=bufSize)
                err_sys("write_error", 0);
            lineCounter++;
        }
    }

    //Finish program
    if (close(fd_openedFile)!=0) err_sys("error closing original file's file descriptor", 0);
    if (close(fd_newFile)!=0) err_sys("error closing new file's file descriptor", 0);
    return 0;
}

В этом коде предполагается, что файл является .txt и что в конце каждой строки есть «разрывная строка», и он в настоящее время находится в разработке.

Еще раз спасибо.

1 Ответ

0 голосов
/ 17 января 2019

Вы не выделяете никакой памяти для miniBuffer, который является массивом char указателей. Что на самом деле не проблема - проблема в том, что это не должен быть массив char указателей. Вам нужно только, чтобы он был массивом символов типа следующего:

char miniBuffer[1];

И еще одно изменение заключается в проверке этого единственного элемента массива на наличие символа \n.

if (miniBuffer[0] == '\n')

Вы можете обнаружить, что было бы более эффективно читать большие куски, увеличив размер массива и используя такие функции, как strchr, чтобы найти любой \n в строке. Вам нужно будет сохранить сумму, возвращаемую read, чтобы вы могли NUL правильно завершить строку.

...