Problems with C File

1

Good afternoon! I have the following code in C:

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

#define tamString 100

void            
cargarArchivo(FILE * archivo, char phrase[tamString]);

int
main()
{
    FILE    *archi;
    archi = fopen("archis.txt", "w+b");
    char    frase[tamString];

    puts("Ingrese una frase");
    fgets(frase, tamString, stdin);


    cargarArchivo(archi, freis);

    fclose(archi);

    return 0;
}

void
cargarArchivo(FILE * archivo, char phrase[tamString])
{

    char     resultado[tamString];
    int      i = 0;
    long int maxLenght = 0;

    fwrite(phrase, sizeof(char), sizeof(phrase), archivo);

    maxLenght = ftell(archivo);
    rewind(archivo);

    fread(resultado, sizeof(char), sizeof(resultado), archivo);

    for (i = 0; i < maxLenght; ++i)
    printf("%c", resultado[i]);

}

The problem is when I want to display the result of fread (), it shows me only 8 or 9 characters, not all the others.

    
asked by Nicolas Mozo 27.05.2016 в 21:31
source

1 answer

2

After giving a little head to your code, plus what Leonon says and everyone who commented, I modified your code a bit using #include <string.h> to check the size with strlen() and the result is what you expect , I do not know if it's part of an exercise you're doing, so I do not know if it's valid to use strlen :

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define tamString 100

void cargarArchivo(FILE * archivo, char phrase[tamString])
{
    char     resultado[tamString];
    int      i = 0;
    long int maxLength = strlen(phrase);

    fwrite(phrase, sizeof(char), maxLength, archivo);

    rewind(archivo);
    fread(resultado, sizeof(char), sizeof(resultado), archivo);

    for (i = 0; i < maxLength; ++i)
        printf("%c", resultado[i]);

}

Currently the problem with your code is here:

fwrite(phrase, sizeof(char), sizeof(phrase), archivo);

The reason is that sizeof(phrase) will always give 8 or 4 as a result because sizeof only returns the number of bytes needed to position a variable in memory, no matter the length of the file, it will always be 8 or 4.

Question in SO
Reference to ftell
Reference to fread

I hope it has helped you.

    
answered by 28.05.2016 в 15:24