msmithy12
Posts: 94
Joined: Fri Aug 10, 2012 8:57 am

Create an output file in c

Tue Mar 05, 2013 9:02 am

Hi, another simple question from a simple forum member :lol:

I want to use some values i`ve collected in my c program (serial no, and some voltage levels) using the serial port and output these values into a text file (csv might be nice but is probably way more effort)

I did a google search and came across

Code: Select all

#include<stdio.h>
int main()
{
FILE *fp;
char ch;
fp=fopen("file.txt","w");
printf("\nEnter data to be stored in to the file:");
while((ch=getchar())!=EOF)
putc(ch,fp);
fclose(fp);
return 0;
}
I assume the code will create a file and store whatever i type into terminal, but i want to understand what each line does (there were no comments on the web)
i assume and correct me where i am wrong and fill in my blanks

'fp' is file properties and works simillarly to 'fd' in serial comms

file.txt is the name of the file to open,

w is a write command??(major guess)

printf and while i have used before

ch = whatever i type into terminal and when that is not equal to EOF (extreamly odd file :D or something more logical)

put ch into fp

fclose(fp) i assume closes the edit of file.txt

By the way that example code creates a file 'file.txt' but no data is stored in it so when i understand the commands that are there I will be able to see what is wrong and modify it to my needs.

Programming is hard, I cant believe I studied to degree level in electronics and c programming was never a topic (I can see why Eben wanted to release the pi)
I assume I know what I`m talking about... I probably don`t

Home: 256mb Made in UK, Rasbmc, 40" Sony Bravia KDL-40v3000
Work: 2b+, Rasbian, 6" Lilliput touchscreen

macsmith
Posts: 13
Joined: Fri Dec 30, 2011 5:12 pm

Re: Create an output file in c

Tue Mar 05, 2013 9:34 am

I used to "eat and drink" C and I used a book called "The C Book". I see the good book is now accessible on the web: http://publications.gbdirect.co.uk/c_book/. I thoroughly recommend it.

The "w" in fopen is the mode with which the file is opened, in this case, write mode. If the file doesn't exist, it will be created. If it already exists, then it will be truncated (read deleted!) and a new one created.

EOF is End of File. From the keyboard, this is ctrl z.

fclose will eventually finish writing to the file and close it. This will happen at an idle moment when the pi isn't doing anything else. Until then, some or all of the data will be sitting in a buffer. If the pi were to crash(!) before then, some or all of the data could be lost. To guarantee that everything has been written, use the fflush(fp) as it will do what its name suggests. This is only normally used in some extreme applications, ie, not needed when experimenting.

Hope that helps but do have a look through the book. It answers absolutely everything!

Ian

User avatar
PeterO
Posts: 5468
Joined: Sun Jul 22, 2012 4:14 pm

Re: Create an output file in c

Tue Mar 05, 2013 9:50 am

msmithy12 wrote: 'fp' is file properties and works simillarly to 'fd' in serial comms
No. fp is a pointer to a FILE. FILE is a structure that holds information about a file.
file.txt is the name of the file to open,

w is a write command??(major guess)
No. The string "w" is a parameter to fopen. fopen interprets the string to determine how to open the file, where how is "w"=wite "r"=read " (man fopen will give you all the possibilities).

A good skill to learn is looking at the manual pages for all these C functions.
Run "man fopen" to get description of the function and its paramaeters.
Running "man XXXXX" should be your first port of call when having problems with XXXXX :-)
PeterO
Discoverer of the PI2 XENON DEATH FLASH!
Interests: C,Python,PIC,Electronics,Ham Radio (G0DZB),1960s British Computers.
"The primary requirement (as we've always seen in your examples) is that the code is readable. " Dougie Lawson

User avatar
[email protected]
Posts: 2020
Joined: Tue Feb 07, 2012 2:14 pm
Location: Devon, UK
Contact: Website

Re: Create an output file in c

Tue Mar 05, 2013 10:06 am

macsmith wrote: EOF is End of File. From the keyboard, this is ctrl z.
It's Control-D on a unix or unix-like system e.g. Linux.

-Gordon
--
Gordons projects: https://projects.drogon.net/

macsmith
Posts: 13
Joined: Fri Dec 30, 2011 5:12 pm

Re: Create an output file in c

Tue Mar 05, 2013 10:16 am

thanks for the ctrl d correction. I was scratching my head on that one. Perhaps it was the old DEC VT100's(?) that used z.

Cheers

Ian

User avatar
[email protected]
Posts: 2020
Joined: Tue Feb 07, 2012 2:14 pm
Location: Devon, UK
Contact: Website

Re: Create an output file in c

Tue Mar 05, 2013 10:26 am

msmithy12 wrote:Hi, another simple question from a simple forum member :lol:

I want to use some values i`ve collected in my c program (serial no, and some voltage levels) using the serial port and output these values into a text file (csv might be nice but is probably way more effort)

I did a google search and came across

Code: Select all

#include<stdio.h>
int main()
{
FILE *fp;
char ch;
fp=fopen("file.txt","w");
printf("\nEnter data to be stored in to the file:");
while((ch=getchar())!=EOF)
putc(ch,fp);
fclose(fp);
return 0;
}
Actually, that program is wrong. It's wrong for a number of reasons, and while it probably works, it's still wrong.

One of the biggest issues with C is that you think the 'char' data type is good for characters - well, odd as this may seem, it's not.... The int data type is often better for characters. (except for arrays of characters or strings - not an issue here though)

So EOF is an int (it's usually -1). the putc() function takes an int and not a char.

The program works here (on some platforms) because the data types are implicitly converted - putc() has a function prototype and the compiler sees this and promotes the char to an int before passing it to the function. The test for EOF works because -1 in an int and char is sometimes signed so the 'ch' value is promoted to an int and the sign bit is preserved.

However... Note that char doesn't have to be signed - it's implementation dependant, and in the implementation on the Pi it's not signed, so this test will fail on a Pi! It works on my x86 Linux desktop where char is signed, but this will not work on a Pi where it's not signed. If you want signed char's then you must explicitly say so: signed char ch;

So if you type this into a Pi, then change the line:

char ch;

into

int ch ;

and it will work as intended. You can use

signed char ch ;

but that will effectively place burden on the compiler as it would then need to insert code to do the conversion from signed char to (signed) int for putc() so you might as well use the data type intended in the first place.

C is great - powerfull, fast, etc. but will trip you up when not looking - even when things look right to you, the C compiler knows better and it's doing exactly what its been told to do (even when you think otherwise ;-)

-Gordon
--
Gordons projects: https://projects.drogon.net/

msmithy12
Posts: 94
Joined: Fri Aug 10, 2012 8:57 am

Re: Create an output file in c

Tue Mar 05, 2013 10:39 am

@peterO you just blew my mind :lol: "man XXXXX" is amazing thanks.

ill also take a look at http://publications.gbdirect.co.uk/c_book/ thanks

i cant believe i've spent 6months writing code and not realised i can man xxxx and get info!

thanks

msmithy12
I assume I know what I`m talking about... I probably don`t

Home: 256mb Made in UK, Rasbmc, 40" Sony Bravia KDL-40v3000
Work: 2b+, Rasbian, 6" Lilliput touchscreen

User avatar
stephj
Posts: 80
Joined: Thu Jun 21, 2012 1:20 pm
Location: Lancashire, UK

Re: Create an output file in c

Tue Mar 05, 2013 11:47 am

On my desk is a rather battered copy of 'C The Pocket Reference' by Herbert Schildt.
Osborne McGraw-Hill 1988 ISBN 0-07-881321-2

I t has a few references to good old MS-DOS but 99% of it is still current. A later version includes C++.

It can still be obtained from second hand online book shops usually for next to nothing.

It is worth its weight in gold. Perfect when you forget the order of parameters on a function etc.

-rst-
Posts: 1316
Joined: Thu Nov 01, 2012 12:12 pm
Location: Dublin, Ireland

Re: Create an output file in c

Tue Mar 05, 2013 12:20 pm

In addition to the Linux command-line, the "man XXXXX" is also amazing when typed in to Google! ;)
http://raspberrycompote.blogspot.com/ - Low-level graphics and 'Coding Gold Dust'

scrapheap
Posts: 20
Joined: Wed Feb 13, 2013 5:13 pm

Re: Create an output file in c

Tue Mar 05, 2013 1:53 pm

macsmith wrote:thanks for the ctrl d correction. I was scratching my head on that one. Perhaps it was the old DEC VT100's(?) that used z.
I believe that DOS/Windows uses ctrl+z to signify an end of file. Back in the days of DOS there were plenty of times when creating a small text file would require us to do something like.

Code: Select all

c:\>copy CON: test.txt
this is a test
of the EOF
^Z
        1 file(s) copied.
At least it was choice between that and edlin :(

User avatar
PeterO
Posts: 5468
Joined: Sun Jul 22, 2012 4:14 pm

Re: Create an output file in c

Tue Mar 05, 2013 5:29 pm

^Z was actually an EOF character (0x1A) that was in the body of the file. It was a hang over from CP/M where the file system only kept a record of the number of blocks in a file not the exact number of bytes. This did mean that if a file exactly filled a number of blocks there might not have been a ^Z at the end.

On Linux/Unix EOF is a condition that occurs when your program tries to read beyond the end of a file. Since "everything is a file" in unix , there has to be a way to signify that the end of the file has been reached a terminal (even thought the file has no size as such). Pressing ^D is the way this is achieved.

PeterO
Discoverer of the PI2 XENON DEATH FLASH!
Interests: C,Python,PIC,Electronics,Ham Radio (G0DZB),1960s British Computers.
"The primary requirement (as we've always seen in your examples) is that the code is readable. " Dougie Lawson

DaveT
Posts: 3
Joined: Wed Mar 06, 2013 1:41 am

Re: Create an output file in c

Wed Mar 06, 2013 2:28 am

Hi msmithy,

The program is fine, with the exception of the unintuitive char vs int for getchar(). As mentioned, man getchar will give you all the details.
msmithy12 wrote:By the way that example code creates a file 'file.txt' but no data is stored in it so when i understand the commands that are there I will be able to see what is wrong and modify it to my needs.
Keep in mind that the as reading from standard input as you are here, you are dealing with buffered input. That is, even though you may be typing, the getchar is not actually processing any of that until you hit return. There are ways to get around that (raw i/o), but I suspect it's more than you want to get into at this point. Try this, run your program, and type: "12345<RETURN><^D>"
you'll see your file.txt has the data:

You've already figured out what most of it does. I took the liberty of anotating and embellishing:

Code: Select all

#include<stdio.h> /* standard I/O functions and pre-defines, etc */

int main()
{
FILE *fp;	 /* File pointer */
int ch;

	/* Open for writing the file file.txt */
	if (NULL == (fp = fopen("file.txt","w"))) {

		/* if it doesn't succeed, exit out */
		printf("Couldn't open file.txt\n");
		return 0;
	}

	printf("\nEnter data to be stored in to the file:");

	/* Read character from standard input, and while it doesn't equal EOF */
	/* write it to the file pointer opened above */
	while((ch=getchar())!=EOF)
		putc(ch,fp);

	
	fclose(fp); /* close the file we opened earlier*/
	return 0; 
}
enjoy,
Dave

User avatar
PeterO
Posts: 5468
Joined: Sun Jul 22, 2012 4:14 pm

Re: Create an output file in c

Wed Mar 06, 2013 9:54 am

-rst- wrote:In addition to the Linux command-line, the "man XXXXX" is also amazing when typed in to Google! ;)
A small thing to watch out for is that with man pages from the net they may belong to different distributions and wrong versions of libraries or programs. The pages displayed by the "man" command do come from your machine and do (*) correspond to the software actually installed on your machine.

PeterO

(*) There is always a small chance that there is a mismatch but it's much, much less likely.
Discoverer of the PI2 XENON DEATH FLASH!
Interests: C,Python,PIC,Electronics,Ham Radio (G0DZB),1960s British Computers.
"The primary requirement (as we've always seen in your examples) is that the code is readable. " Dougie Lawson

User avatar
rurwin
Forum Moderator
Forum Moderator
Posts: 4258
Joined: Mon Jan 09, 2012 3:16 pm
Contact: Website

Re: Create an output file in c

Wed Mar 06, 2013 10:21 am

msmithy12 wrote:(csv might be nice but is probably way more effort)
Actually it is very easy:

Code: Select all

int main()
{
FILE *fp;    /* File pointer */
double x = 3.14, y = 5.67, z = 99.1;
char * s = "Hello world";

   /* Open for writing the file file.txt */
   if (NULL == (fp = fopen("file.txt","w"))) {

      /* if it doesn't succeed, exit out */
      printf("Couldn't open file.txt\n");
      return 0;
   }

   fprintf(fp, "%f, %f, %f, \"%s\"\n", x, y, z, s);    /* write the CSV data to the file */

   fclose(fp); /* close the file we opened earlier*/
   return 0;
}
fprintf is the same as printf, but does it to a file instead of stdout. It's first parameter is the FILE* of the file. \" is an escape sequence like \n to get a quote character into a string.

CSV data is just data separated by commas. Strings have to be surrounded by quote marks if they contain commas, but you can just always include them. Each line of the file corresponds to one row of data. So the above program creates a file with one row of data comprising four values: three numbers and a string.

User avatar
rpdom
Posts: 16135
Joined: Sun May 06, 2012 5:17 am
Location: Chelmsford, Essex, UK

Re: Create an output file in c

Wed Mar 06, 2013 1:00 pm

PeterO wrote:
-rst- wrote:In addition to the Linux command-line, the "man XXXXX" is also amazing when typed in to Google! ;)
A small thing to watch out for is that with man pages from the net they may belong to different distributions and wrong versions of libraries or programs. The pages displayed by the "man" command do come from your machine and do (*) correspond to the software actually installed on your machine.

PeterO

(*) There is always a small chance that there is a mismatch but it's much, much less likely.
The man pages on http://manpages.debian.net/cgi-bin/man.cgi should (mostly) be correct for Raspbian packages.

The advantage of web-based pages is that you can look up the usage of software that you haven't got installed (yet) and decide if it will do what you need.

User avatar
PeterO
Posts: 5468
Joined: Sun Jul 22, 2012 4:14 pm

Re: Create an output file in c

Wed Mar 06, 2013 2:05 pm

rpdom wrote: The man pages on http://manpages.debian.net/cgi-bin/man.cgi should (mostly) be correct for Raspbian packages.
Yes, but I was specifically commenting on the suggestion to use google to find manual pages where you could end up anywhere......
PeterO
Discoverer of the PI2 XENON DEATH FLASH!
Interests: C,Python,PIC,Electronics,Ham Radio (G0DZB),1960s British Computers.
"The primary requirement (as we've always seen in your examples) is that the code is readable. " Dougie Lawson

-rst-
Posts: 1316
Joined: Thu Nov 01, 2012 12:12 pm
Location: Dublin, Ireland

Re: Create an output file in c

Wed Mar 06, 2013 2:40 pm

PeterO wrote:A small thing to watch out for is that with man pages from the net they may belong to different distributions and wrong versions of libraries or programs.
rpdom wrote:The man pages on http://manpages.debian.net/cgi-bin/man.cgi should (mostly) be correct for Raspbian packages.
Valuable additions.
http://raspberrycompote.blogspot.com/ - Low-level graphics and 'Coding Gold Dust'

Return to “C/C++”