2

i am using this function to read from a notepad file and fill the data in char str[255] but after I execute the function str is still empty.

char str[255]; char* data_pull() { std::ifstream in("C:/myfile.txt"); if(!in){ printf("\nCannot open the file"); exit (1); } while(in){ in.getline(str, 255); printf(str); } in.close(); return str; } 
3
  • What is the output of printf(str)? BTW, never use printf(str) for str read from external input, since str might contain formatting code like "%s", better use puts(str) or printf("%s", str). How do you see that the string returned is empty? Just a question aside: could it be that the last line in the text is an empty line? Commented Nov 26, 2012 at 8:56
  • printf(str) is giving me the right output but when i use str in some other function than i get to know that str is empty Commented Nov 26, 2012 at 9:04
  • @sumit kang: This happens because your file ends in an empty line, so the last value stored in str is that empty line. Nothing strange here. Commented Nov 26, 2012 at 9:09

1 Answer 1

4

With in.getline(str, 255); you keep overwriting str for every line in the input file: in other words, every line will overwrite the previous line stored in str.

If the file ends with an empty line, then str will store an empty string at the end of the loop.

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

3 Comments

Not quite correct; I've tested the code on a file with a non-empty last line, and the buffer is still empty.
@csl: The file you used had empty last line. You simply didn't realize that. If the last "line" in your file ends with end-of-line marker (platform-specific, like CR+LF on Windows), then your file has one more line that is empty and is followed by <EOF>. If you want to create a file with truly non-empty last line, you need a file that has no end-of-line marker at the end of the last line, like "SomeData<EOF>". Have you tried that?
@AndreyT vim didn't show any trailing newline, but sure enough echo -ne "hello\nworld" > test worked out allright. Thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.