简体   繁体   English

C-文件输入/验证LINUX / Windows问题

[英]C - File Input/Validation LINUX/Windows Issue

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. 问题在于validatehex函数中,即使该值正确,它也始终会打印“不正确”。 This code works 100% perfect in windows put not in linux(Ubuntu). 此代码在Windows(而不是Linux(Ubuntu))中可以100%完美地工作。

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. 我已经使用mingw32 c编译器在Windows上进行了尝试,并且效果很好。 The file it reads from just consists of hex values which are 8 digits long on each line. 它从中读取的文件仅由每行8位数字的十六进制值组成。

Can anyone see where the code is going wrong? 谁能看到代码出了什么问题? Or why it is working differently within Linux? 还是为什么它在Linux中的工作方式不同?

Linux and Windows use different end-of-line markers: Windows uses \\r\\n while Linux uses \\n . Linux和Windows使用不同的行尾标记:Windows使用\\r\\n而Linux使用\\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. 如果要读取在Linux上用Windows编写的文件,则在字符串末尾会得到一个额外的\\r

This is one way to avoid the problem: 这是避免该问题的一种方法:

int len = strlen(input);
if (input[len-1] == '\r') input[len-1] = '\0';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM