001
02.10.2002, 12:24 Uhr
void*
Generic Pointer (Operator)
|
Hallo!
Hier auch mal ein Beitrag von mir ... Ist nicht schön, aber "straightforward" und simpel.
C++: |
#include <cstdio> #include <string>
// ...
// Description: This function deletes a line out of a file. // Parameters: name of the file out of which a line shall be deleted, // number of line to be deleted (count starts at 0) // Return value: number of characters that were deleted (including '\n'), -1 // file could not be opened for reading, -2 error reading file, -3 error opening // file for writing, -4 error writing file, 0 line number 'line' does not exist int delline(const char* name, size_t line) { // read the whole file and write it into buffer std::FILE *input=std::fopen(name, "r"); if(!input) return(-1);
std::string buffer; int c;
while(EOF!=(c=fgetc(input))) { buffer+=static_cast<char>(c); }
if(!feof(input)) // Builder doesn't want eof() in std?! { (void)std::fclose(input); return(-2); }
if(EOF==std::fclose(input)) return(-2);
// search the start of the line that has to be deleted unsigned int currentLine=0; std::string::size_type currentPosition=0, oldPosition=0;
while(currentLine<line) { currentPosition=buffer.find_first_of('\n', oldPosition); if(std::string::npos==currentPosition) return(0); oldPosition=++currentPosition; if(buffer.length()<=oldPosition) return(0); ++currentLine; }
// find the end of the current line std::string::size_type endPosition=buffer.find_first_of('\n', currentPosition); // determine number of chars to be deleted...and get rid of them int numberOfCharsDeleted= std::string::npos==endPosition ? buffer.length()-currentPosition : endPosition-currentPosition+1; buffer.erase(currentPosition, numberOfCharsDeleted);
// write the modified buffer std::FILE *output=std::fopen(name, "w"); if(!output) return(-3);
if(0>fprintf(output, "%s", buffer.c_str())) { (void)std::fclose(output); return(-4); }
if(EOF==std::fclose(output)) { return(-4); }
return(numberOfCharsDeleted); }
|
MfG void* -- Gruß void* |