Monday, May 24, 2010

C program blank removal?

last program and I am done guyz, can someone please help me. i hav been doin this all night, in C not C++. thank you very much really appreciate it.





A text file contains a bunch of characters. There are no tab characters within the file.





Write a program that replaces two or more consecutive blanks by a single blank. For example, if the input is





Let’s go to the movies.





then the output would be Let’s go to the movies.





The input from this program should come from a file whose name has been supplied via argv[1]. The output from this program should go to standard output. Note: This program came from Chapter 3 in your ANSI C text book.

C program blank removal?
I'm really reluctant to just give you the answer - it's clear this is for some coursework, so I'll give you a framework and hints. You fill out the TODOs.





#include %26lt;stdio.h%26gt;


int main(int argc, char **argv)


{


int fd;


char buffer[1024];


char outbuffer[1024];


int n;


char *bp,*obp;


int isspace;





TODO check the value of argc


TODO fd = open the file argv[0] in the correct mode


TODO check the value of fd, display an error (perror is a good choice for this) and exit if fd indicates an error.


n = read(fd, buffer, 1024);


(We're just going to do a one off read of 1k. Better still would be to loop around getting buffers and checking their contents as we go. You can figure this out, but if you do, handle the case where one space is in one buffer and another space is in the next one. Remember that 'n' may not come back with 1024 - it could be -1 if there's an error, or a number between 0 and 1024 if the file is smaller than 1k.)


TODO - check the value of n doesn't indicate an error. If it does, display an error and close fd


close fd





At this point you have 'n' bytes of your file in the buffer. Loop around looking for spaces.





isspace=0;


for (bp=%26amp;buffer[0], obp=%26amp;obuffer[0]; n%26gt;0; bp++, n--)


{


if (*bp==' ')


{


if (isspace)


{


we had a space last time, now here's another. Don't copy *bp to *obp


isspace=0;


continue;


}


else


{


isspace=1;


}


}


*obp=*bp;





(for clarity, on its own line)


obp++;





}





TODO - what do you want to do with your new buffer?





return 0;


}

verbena

No comments:

Post a Comment