From: michael DOT mauch AT gmx DOT de (Michael Mauch) Newsgroups: comp.os.msdos.djgpp Subject: Re: Newbie question -- debug this plz Date: Sun, 12 Jul 1998 17:47:04 +0200 Organization: Gerhard-Mercator-Universitaet -GH- Duisburg Lines: 76 Message-ID: <6oalp1$np2$1@news-hrz.uni-duisburg.de> References: <35A8106A DOT 6B1FD58D AT bc DOT sympatico DOT ca> NNTP-Posting-Host: ppp182.uni-duisburg.de Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit To: djgpp AT delorie DOT com DJ-Gateway: from newsgroup comp.os.msdos.djgpp Precedence: bulk On Sat, 11 Jul 1998 18:24:59 -0700, Jim Barlow wrote: > I'm trying to write a program that does this (again, C, DJGPP): > 1) takes the first command line parameter as a filename (obvious) > 2) opens the file. coughs up an error if any. File is binary and can contain > nulls in-line. Also very large (~500 kb). Hmm, 500 KB is not very large. With DJGPP, you can read that file into memory without problems. > 3) reads the file into a buffer. Search for a specific string. If found it > needs to be able to write to that offset. > 4) write changes to the file without corrupting anything. It's overwritting > information, not inserting anything new. > > FILE *fp; > char *my_buffer, *offset; > if (argc) { > fp = fopen (argv[1], "rb+"); // or whatever open for read/write binary is > if (ferror (fp)) { > printf ("There was an error..."); > return; > } That's a bad idea: if fopen() returns a NULL pointer (what it does in case of an error), your ferror() will crash. The normal way is: if (!fp) { perror("There was an error"); return EXIT_FAILURE; } > // best way to read the data into my_buffer? > my_buffer = offset = (char *)malloc (sizeof(char) * > func_that_gets_file_size(fp)); A portable function that is suitable for files with up to 2 GB: long func_that_gets_file_size(FILE* fp) { fseek(fp,0,SEEK_END); return ftell(fp); } You could use fsetpos()/fgetpos() for larger files. > readinto(fp); // should i use fread() or something else? Yes, if your file is only 500 KB, you can fread() it completely into memory. If you have a file that is larger than your RAM, you will get a speed penalty because of swapping, but that's not a problem here. > strchr (offset, "my_string"); strchr() is a bad idea because the string functions (str...) all stop at the first NUL character. memchr() is suitable. > if (offset) { > strcpy (offset, "newstring"); > } > // write buffer to file Just fwrite() it out again. > } And don't forget to fclose() the file. > Thanks for your patience. No problem; have a look at the libc reference for the functions I pointed out. Regards... Michael