Search code examples
cfgets

why does fgets() keep skipping last letter when I dont have an empty line at the end?


I want to get every line and put it in my array. This works when I have an empty line at the end of the file, but I need to be able to process all lines without having a line at the end. When I read the file the x is missing at the end of ax on the last line. This is the file used:

read ax
mul 2 ax
print ax

the file I get with my code: read ax mul 2 ax print a

This is what I have at the moment. How can I fix this?

int row = 100;
int columns = 100;
char operation[row][columns];
FILE *fp = fopen(argv[1],"r");
//populates matrix of assembly code
while(fgets(operation[i],columns, fp)!=NULL){
    operation[i][strlen(operation[i])-1] = '\0';
    i++;
} numberOfLines = i;

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

Solution

  • operation[i][strcspn(operation[i], "\r\n")] = '\0';
    

    This will set the first '\r' or '\n' to '\0'

    https://en.cppreference.com/w/c/string/byte/strcspn