Reputation: 3794
FILE *f;
char buffer[201];
f=fopen("file.txt","r");
if (f==NULL)
{
printf("file doesn't exist?!\n");return 1;
}
while(1)
{
if ((fgets(buffer, 200, f) == NULL))
break;
instruction = validatehex(buffer);
if(instruction == - 1)
continue;
PC += 4;
Decode(instruction,verbose);
}
The above code gets the input from the file line by line validating it. The problem is in the validatehex function it always prints "Not correct" even if the value is correct. This code works 100% perfect in windows put not in linux(Ubuntu).
uint32_t validatehex(char input[])
{
char hexchars[] = "1234567890abcdefABCDEF";
uint32_t hexvalue = 0;
char last;
if((strlen(input) != strspn (input,hexchars)) && ((strlen(input)-1 != strspn (input,hexchars)) && input[8] != '\0'))
{
printf("NO CORRECT\n");
return INERR;
}
sscanf(input,"%08x",&hexvalue);
return hexvalue;
}
I've tried it across to windows with mingw32 c compiler and it works perfect. The file it reads from just consists of hex values which are 8 digits long on each line.
Can anyone see where the code is going wrong? Or why it is working differently within Linux?
Upvotes: 0
Views: 620
Reputation: 6919
Linux and Windows use different end-of-line markers: Windows uses \r\n
while Linux uses \n
. What kind of linebreaks does your file use?
If you are reading a file written in windows on Linux, you will get an extra \r
at the end of the string.
This is one way to avoid the problem:
int len = strlen(input);
if (input[len-1] == '\r') input[len-1] = '\0';
Upvotes: 1