home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #27 / NN_1992_27.iso / spool / comp / lang / c / 16868 < prev    next >
Encoding:
Text File  |  1992-11-20  |  1.8 KB  |  61 lines

  1. Newsgroups: comp.lang.c
  2. Path: sparky!uunet!unipalm!tim
  3. From: tim@unipalm.co.uk (Tim Goodwin)
  4. Subject: Re: write an int?
  5. Message-ID: <1992Nov20.130740.10290@unipalm.co.uk>
  6. Organization: Unipalm Ltd., 216 Cambridge Science Park, Cambridge CB4 4WA, UK
  7. References: <Nov.19.19.08.57.1992.14534@ratt.rutgers.edu>
  8. Date: Fri, 20 Nov 1992 13:07:40 GMT
  9. Lines: 50
  10.  
  11. map@ratt.rutgers.edu (O. C.) writes:
  12.  
  13. >I want to write an integer to a text file using the Unix system call
  14. >write,
  15.  
  16. >write(file descriptor,buffer,size);
  17.  
  18. >but I can only seem to get it to work for strings and characters.
  19.  
  20. >What am I doing wrong?
  21.  
  22. Who knows?  Had you included a fuller description of the problem,
  23. including a few lines of actual code that demonstrate it, it might be
  24. possible to say.
  25.  
  26. If you've instantiated "file descriptor" with a valid file descriptor,
  27. and "buffer" with the address of an int, and "size" with the sizeof an
  28. int, and if the system call returned the same size you gave it, then
  29. the int will eventually show up in the file/device/whatever that the
  30. file descriptor refers to.
  31.  
  32. Note that: UNIX system calls are unlikely to exist on anything but a
  33. UNIX machine; even on another UNIX machine, you will probably not be
  34. able to read back the int; even if you know that you will never ever
  35. want to do either of these, slinging binary data around makes
  36. debugging hard, and is generally a Bad Thing.
  37.  
  38. What you probably want to do is something like this.
  39.  
  40.     #include <stdio.h>
  41.     #include <stdlib.h>
  42.     int main(void)
  43.     {
  44.         FILE *fd;
  45.         int myint = 42;
  46.  
  47.         fd = fopen("somefile", "w");
  48.         if (!fd) {
  49.             perror("somefile");
  50.             return(EXIT_FAILURE);
  51.         }
  52.         fprintf(fd, "%d\n", myint);
  53.         fclose(fd);
  54.         return(EXIT_SUCCESS);
  55.     }
  56.  
  57. Note that I am ignoring the return values of fprintf() and fclose(),
  58. which is rather sloppy.
  59.  
  60. Tim.
  61.