home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c
- Path: sparky!uunet!unipalm!tim
- From: tim@unipalm.co.uk (Tim Goodwin)
- Subject: Re: write an int?
- Message-ID: <1992Nov20.130740.10290@unipalm.co.uk>
- Organization: Unipalm Ltd., 216 Cambridge Science Park, Cambridge CB4 4WA, UK
- References: <Nov.19.19.08.57.1992.14534@ratt.rutgers.edu>
- Date: Fri, 20 Nov 1992 13:07:40 GMT
- Lines: 50
-
- map@ratt.rutgers.edu (O. C.) writes:
-
- >I want to write an integer to a text file using the Unix system call
- >write,
-
- >write(file descriptor,buffer,size);
-
- >but I can only seem to get it to work for strings and characters.
-
- >What am I doing wrong?
-
- Who knows? Had you included a fuller description of the problem,
- including a few lines of actual code that demonstrate it, it might be
- possible to say.
-
- If you've instantiated "file descriptor" with a valid file descriptor,
- and "buffer" with the address of an int, and "size" with the sizeof an
- int, and if the system call returned the same size you gave it, then
- the int will eventually show up in the file/device/whatever that the
- file descriptor refers to.
-
- Note that: UNIX system calls are unlikely to exist on anything but a
- UNIX machine; even on another UNIX machine, you will probably not be
- able to read back the int; even if you know that you will never ever
- want to do either of these, slinging binary data around makes
- debugging hard, and is generally a Bad Thing.
-
- What you probably want to do is something like this.
-
- #include <stdio.h>
- #include <stdlib.h>
- int main(void)
- {
- FILE *fd;
- int myint = 42;
-
- fd = fopen("somefile", "w");
- if (!fd) {
- perror("somefile");
- return(EXIT_FAILURE);
- }
- fprintf(fd, "%d\n", myint);
- fclose(fd);
- return(EXIT_SUCCESS);
- }
-
- Note that I am ignoring the return values of fprintf() and fclose(),
- which is rather sloppy.
-
- Tim.
-