2

in my project I used arrays not pointers. My purpose is here copy all characters one-by-one from text.file into array. I found some examples from the Internet, this site but none of them was useful for me. Think that input1.txt is "abcd" I want like these input1[0] = a, input1[1] = b, etc.

main ()
{
    FILE *f1 = fopen("input1.txt", "r");
    int i;
    fseek(f1, 0, SEEK_END); 
    int inputsize = ftell(f1); //its about text's size
    char input1[inputsize];
    for(i = 0; i < inputsize; i++)
    {
          fscanf(f1, "%c", &input1[i]);
    }
    printf("%c ", input1[3]);
    getchar();
}

When I run this code it doesn't print "d", but prints "6". Why is this happening? What should I do? Thanks for help

3
  • Check what fopen returns Commented May 11, 2014 at 9:52
  • It returns pointer. Must I use pointer? but I made all project according to array. I can not change it. Today is due date. Is any other way to solve this problem? Commented May 11, 2014 at 10:01
  • Your own way is good. Note that ftell returns long int type not int type.. Commented May 11, 2014 at 10:27

2 Answers 2

4

You seek to the end of the file to obtain it's size, but don't seek back to the start of the file again before you start actually reading it.

Insert just before your loop:

fseek(f1,0,SEEK_SET);

Pasting your code into my compiler with this amendment worked on my machine

Sign up to request clarification or add additional context in comments.

2 Comments

@user119949: Welcome to SO! Your status suggests you have not yet read About Stackoverflow. Please do so at your convenience; it won't take too much of your time. Pay particular attention to the paragraph about accepting an answer.
Great don't forget to accept the answer if you want to thank :-)
2

You could also use a function rewind(FILE*) instead of doing an fseek() again.

Worth noting should be the fact that you're allocating an array with a variable, which might be a bad idea in this case (especially when you could be reading a bigger file than one with 4 characters).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.