©2004 by Marc J. Rochkind. All rights reserved. Portions marked "Open Source" may be copied under license.

 

Main Page   Modules   Namespace List   Class Hierarchy   Compound List   File List   Namespace Members   Compound Members   File Members  

c2/trunc.c

Go to the documentation of this file.
00001 /*
00002     ftruncate test program
00003     AUP2, Sec. 2.17 (not in book)
00004 
00005     Copyright 2003 by Marc J. Rochkind. All rights reserved.
00006     May be copied only for purposes and under conditions described
00007     on the Web page www.basepath.com/aup/copyright.htm.
00008 
00009     The Example Files are provided "as is," without any warranty;
00010     without even the implied warranty of merchantability or fitness
00011     for a particular purpose. The author and his publisher are not
00012     responsible for any damages, direct or incidental, resulting
00013     from the use or non-use of these Example Files.
00014 
00015     The Example Files may contain defects, and some contain deliberate
00016     coding mistakes that were included for educational reasons.
00017     You are responsible for determining if and how the Example Files
00018     are to be used.
00019 
00020 */
00021 #include "defs.h"
00022 
00023 #define TEXTLINE "This is a line.\n"
00024 
00025 static int fd = -1;
00026 
00027 void buildfile(void)
00028 {
00029     int i;
00030 
00031     /* Build original file. */
00032     if ((fd = open("a.tmp", O_RDWR | O_CREAT | O_TRUNC, PERM_FILE)) == -1)
00033         syserr("open");
00034     for (i = 0; i < 5; i++)
00035         if (write(fd, TEXTLINE, strlen(TEXTLINE)) == -1)
00036             syserr("write");
00037 }
00038 
00039 int main(void)
00040 {
00041     off_t pos_in, pos_out;
00042     char c;
00043 
00044     buildfile();
00045     printf("Original file:\n");
00046     system("cat a.tmp");
00047 
00048     pos_in = pos_out = 0;
00049 
00050     while (true) {
00051         if (lseek(fd, pos_in, SEEK_SET) == -1)
00052             syserr("lseek to pos_in");
00053         if (read(fd, &c, 1) != 1)
00054             break;
00055         pos_in++;
00056         if (c != ' ') {
00057             if (lseek(fd, pos_out, SEEK_SET) == -1)
00058                 syserr("lseek to pos_out");
00059             if (write(fd, &c, 1) == -1)
00060                 syserr("write at pos_out");
00061             pos_out++;
00062         }
00063     }
00064     printf("\nSqueezed file, not truncated:\n");
00065     system("cat a.tmp");
00066 
00067     if (ftruncate(fd, pos_out) == -1)
00068         syserr("ftruncate");
00069     printf("\nSqueezed file, truncated:\n");
00070     system("cat a.tmp");
00071 
00072     if (close(fd) == -1)
00073         syserr("close");
00074     exit(EXIT_SUCCESS);
00075 }

Generated on Fri Apr 23 10:56:54 2004 for AUP2 Example Source by doxygen 1.3.1