I want to read the first line of one txt file and save it to hexArray.

The line contains 32 characters representing a hexadecimal number.

I have the following code:

#include <stdio.h>
#include <stdlib.h>
#include "gmp.h"

char *saveToArray(FILE *hexFile);

int main(int argc, char* argv)
{
    char ch;
    FILE *hexFile = fopen("hex.txt", "rb"); //recebido pela consola
    char *hexArray = saveToArray(hexFile);
    for(int i = 0 ; i < 32; i++)
    {       
        printf("%c", hexArray[i]);
    }
    printf("\n%d", sizeof hexArray);

    ch = getchar();
    return 0;
}

char *saveToArray(FILE *hexFile)
//metodo que devolve uma array contendo uma linha do ficheiro
{
    char hexArray[32];
    fgets(hexArray, sizeof hexArray, hexFile);  
    return hexArray;
}

It seems to be okay, but the output shows that it isn't.

Please help me solve this.

Thanks! Cumps.

有帮助吗?

解决方案

You must make hexArray static either by doing this:

char *saveToArray(FILE *hexFile)
//metodo que devolve uma array contendo uma linha do ficheiro
{ 
    static char hexArray[32];
    fgets(hexArray, sizeof hexArray, hexFile);  
    return hexArray;
}

Or, by doing this:

char hexArray[32];
int main(int argc, char* argv)
{
    char ch;
    ...
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top