Search code examples
cstringfilepointersfile-descriptor

How to replace successive occurrences of characters in a file by the number


In my code, I successfully opened the file, but now I don't understand how to perform a loop using the read() function, to get all the characters in file1. I set a buffer of size 8, but the file contents are more.

Thanks. Also please help me do this using syscalls like that


Solution

  • You are getting confused between a char and a pointer to a char:

    char *buffer[4096];
    

    Is an array of pointers to chars, an is supposed to hold pointers, not chars. What you want is an array of char:

    char buffer[4096];
    

    Now when you add the \0 you will get a compiler error. This also means that it contains a string, meaning you use the %s conversion for printf to print it, no loop involved, just do:

    printf("%s", buffer);
    

    Also, do your read like this (again no loop needed):

    ssize_t count = read(fd1, buffer, sizeof buffer - 1);
    if(count < 0)
        return -1;
    

    This will read up to 4095 bytes into your array, depending on the size of the file. This leaves room for your \0.

    So to make sure you read all your file, do something like:

    ssize_t count;
    while((count = read(fd1, buffer, sizeof buffer - 1)) != 0)
    {
        if(count < 0)
            return -1;
    
        buffer[count] = '\0';
        printf("%s", buffer);
    
        // Do your processing here
    }
    

    The idea is to read a chunk from the file, then process it as required, then read another chunk etc. When the end of the file is reached, read will return 0 and your processing will stop.

    An equivalent way to do this loop, which may be easier to understand is:

    ssize_t count = read(fd1, buffer, sizeof buffer - 1);
    while(count != 0)
    {
        // .....
    
        count = read(fd1, buffer, sizeof buffer - 1);
    }
    

    This makes it more clear that you are looping until count is zero. The trick I have used is to take the count = read(...) part and put it inside the parentheses. The result of evaluating what is inside the parentheses (count = read(...)), is the result of the assignment (ie what gets assigned to count, which is the result of read). Putting this inside while statement means the part in parentheses gets evaluated first (ie it does the read and assigns count). The the result of the assignment (ie count) then gets checked to see if it is zero.