Hi,
I have a file "a.txt". I want to read the contents of the file line by line and output them. a.txt has the following input:
a.txt:
Text
file
1
2
3
Can anyone help me, how can I use fscanf and fprintf to read and output these files? Thanks
Hi,
I have a file "a.txt". I want to read the contents of the file line by line and output them. a.txt has the following input:
a.txt:
Text
file
1
2
3
Can anyone help me, how can I use fscanf and fprintf to read and output these files? Thanks
Smells like homework. Did you try it yourself?
Use a loop:
1. Read a line (attempt to read a line).
2. If successfull, output it. If not, exit loop.
3. Rinse, repeat.
"Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
-Christopher Hitchens
In Windows, there are actually two chars at the end of a line: \xD and \xA. Note, they exist only in text files. But in *nix, only one: \xA. So you can open a.txt with binary mode, and read a line by comparing current char with \xD or \xA (under *nix).
Last edited by TalosChen; 05-09-2006 at 10:59 AM.
> Can anyone help me, how can I use fscanf and fprintf to read and output these files?
fgets() and fputs() would be better
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
I don't know how can someone "smell" a homework. If you do not know the answer please say so instead of showing off to other people how good you are. I have done programming in C++ and Visual in span across advanced conpets like hashing, stacks, queue, collection, btree, graph problems etc. Its just that I am trying to convert this program from Fortran to C and I am not familiar with some of the formats of C.
For example Fortran reads a line sequentially using the following statement:
read(10, 200) project_name
What I wanted to know if fscanf it works the same way in C? i.e. if fscanf takes a line at a time like the fortram read statement.
It can, provided you know how long the string is. This will read LEN characters and a turminating NUL character into string. And then read a newline and do nothing with it.
However this is not the best practice. If you get input shorter than LEN characters it won't work as good because the \n gets put in the string buffer, and then fscanf reads to the end of the file or until the buffer is filled.Code:fscanf(fp, "%*s\n", LEN, string);