Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue with removing new lines & printf

A txt file is read in binary mode and stored in a buffer (I'm writing a HEX editor so it's important that files are read in binary mode):

original file

The following code removes any new lines and prints the txt to the console:

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>

FILE *fileptr;
unsigned char *buffer;
long filelen;

int main(int argc, char* argv[]){

    fileptr = fopen(argv[1], "rb");
    fseek(fileptr, 0, SEEK_END);
    filelen = ftell(fileptr);
    rewind(fileptr);

    buffer = (char *)malloc((filelen+1)*sizeof(char));
    fread(buffer, filelen, 1, fileptr);
    fclose(fileptr); // Close the file

    for (int i = 0; i < filelen; i++){
        if (buffer[i] == '\n'){
            printf(".");
        }else{
            printf("%c", buffer[i]);
        }
    }
}

This is the intended output, what we want: expected output

This is the actual output, not what we want: incorrect/actual output

When a sleep(); command is added this is what seems to be occurring(Second line highlighted in green for clarity):

enter image description here

The first line prints fine, then the new line is reached, this is where the error is occurring the new line seems to be removed, only the cursor jumps back to the beginning of the line, this behavior is not expected nor is it wanted.

like image 563
GCaldL Avatar asked Nov 30 '25 14:11

GCaldL


1 Answers

Try this

for (int i = 0; i < len; a++){
    if ((buffer[i] == 10) || (buffer[i]==13)){
        printf(".");
    }else{
        printf("%c", buffer[a]);
    }
    fflush(stdout);
}

as you know unix, dos and mac .txt files have different ways of indicating the start of a new line and this could be causing an issue for you - In the revised code instead of looking for \n the program looks for ascii codes 10 and 13 - line feed and carriage return. The one undesirable consequence is that you will get two .s between lines for ms-dos type files, but you could modify around that provided you knew you would only ever have ms-dos type .txt files

The other thing I have added that may or may not be necessary is fflush(stdout); because often when you printf things do not appear immediately on the screen and this should force things to be printed. It may not be necessary.

I think the reason that you get one line written on top of the other is because you have a dos type .txt file with a carriage return and a linefeed character at the end of each line - you are catching the linefeed with your \n if statement, but not the carriage return which sends the cursor to the beginning of the line and means that the first part of the text file is overwritten by the second part.

like image 140
tom Avatar answered Dec 02 '25 04:12

tom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!