Use fgets to read file




















Learn to implement data structures like Heap, Stacks, Linked List and many more! Check out our Data Structures in C course to start learning today.

Recommended Articles. Article Contributed By :. Easy Normal Medium Hard Expert. Writing code in comment? You can see that, this time, we can print full lines of text and not fixed length chunks like in the initial approach.

However, you should be able to test it if you are using Cygwin or Windows Subsystem for Linux. Also, calling getline more than once will overwrite the line buffer, make a copy of the line content if you need to keep it for further processing.

It is interesting to note, that for this particular case the getline function on Linux resizes the line buffer to a max of bytes. If you run the same code on macOS the line buffer is resized to bytes. This is due to the different ways in which getline is implemented on different Unix like systems.

As mentioned before, getline is not present in the C standard library. It could be an interesting exercise to implement a portable version of this function.

In lines , if statement is used to test the value of fp. If it is NULL , printf statement prints the error message and program terminates. Otherwise, the program continues with the statement following the if statement. In lines , a while loop is used to read the contents of the myfile2. Here is how while loop works:. The function fgets is called with an argument of 30, so it reads 29 characters from the file, stores them in the array str by appending null character at the end.

Find centralized, trusted content and collaborate around the technologies you use most. Connect and share knowledge within a single location that is structured and easy to search.

Now, when I put every string, in the last string I am getting repetition and some more ambiguities like something else also gets printed say or so. You need to check the return value of fgets. If a read has been successful, fgets returns the pointer to the buffer that you passed to it i. The eof is only reached after you have attempted to read from a file that is at the end.

You have to use the return value of fgets instead which returns NULL on eof or error and the pointer it is given otherwise :. Checking the return value like this will cause you never to hit the eof inside the body of the loop, like the other one, instead of in the condition.

Stack Overflow for Teams — Collaborate and share knowledge with a private group. Create a free Team What is Teams? Collectives on Stack Overflow.



0コメント

  • 1000 / 1000