0
votes

Why is my program returning me 9 when the file has "test1" written? The program looks for number of characters within the file. I wanted to run off the 'while(fgetc(file) != EOF)' method but this seems not to be working.

I would appreciate some help on this. Thank you

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

#define FORMATLOG "FORMAT ERROR: invalid parameter: s5e4 <filename.txt>"
#define TXFILELOG "FILE ERROR: Can't open file or file does not exist"

enum { true, false };


int interface(char *filename) {

    FILE *f_text = fopen(filename, "r+");
    size_t size;
    char c;

    if(f_text == NULL) {
        puts(TXFILELOG);
        return NULL;
    }

    fseek(f_text, 0, SEEK_END);
    size_t length = (size_t) ftell(f_text);

    printf("%d", length);

    fclose(f_text);

    return true;
}


int main(int argc, char **argv) {

    if(argc != 2) {
        puts(FORMATLOG);
        return false;
    }

    return interface(argv[1]);
}
1
The 9 be including other characters such as newlines and carriage returns. What does ls -l say the size of the file is? - DanielGibbs
Open the file in a hex editor and check for newlines etc - Angus Comber
in general, this line: enum { true, false }; is backwards as normally false is 0, so the line should be enum { false, true }; - user3629249
in function 'interface' NULL is not a valid return value for main() to use, so better to use 'perror( "fopen" ); exit(1); - user3629249
all the return statements in both functions (effectively, due to the enum) return 0, perhaps not what is actually wanted. - user3629249

1 Answers

0
votes

Why the complication??

See http://linux.die.net/man/2/stat

i.e.

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>

int main()
{
    struct stat buf;
    stat("filename", &buf);
    printf("Size:%d\n", buf.st_size);
    return 0;
}

(oops missed out the error check but I guess you get the picture)