0

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]);

}

Julian Romero
  • 31
  • 1
  • 7

1 Answers1

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

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

https://www.tutorialspoint.com/c_standard_library/c_function_strcspn.htm

Fredrik
  • 1,389
  • 1
  • 14
  • 32