How to Create file but if name exists add incremental number to file name
Hi Team,
i am new to Qt.
How to create a file in given path and if file already exists in the given path then we have to add incremental number to file name.
How to achieve this in Qt?
Ex. if i have to save file "QtFile.txt"
but if file already exists in given path then file has to be saved as "QtFile1.txt".
Regards,
Anamika
Re: How to Create file but if name exists add incremental number to file name
You can check if the file exists using QFile::exists(filename) and if yes, you can add to the new file a new name.
Code:
if(QFile::exists(new_file
) { new_file = “Qtfile.txt1.txt);
}
And then create the file
Re: How to Create file but if name exists add incremental number to file name
Here is a somewhat more complete way to do this with any file, which will create a new filename with a number suffix that is one greater than the suffix of the name that was passed in. This code is not tested, so there may be "off-by-one" errors in computing string lengths and positions. It also does not correctly handle the case where a filename has no extension but end in a ".". That is easy to fix but it is a good exercise to find where to do it.
Code:
(
QFileInfo fInfo
( testName
);
// Use QFileInfo to test and manipulate filename if ( !fInfo.exists() ) // File does not exist, so use it
return testName;
// Retrieve the extension
// and the left-hand side of the path
if ( ext.isEmpty() ) // if there is no extension, then the left side is the whole name
path = testName;
else // otherwise it is everything left of the "."
path = testName.left( testName.lastIndexof( '.' ) );
// Now, start at the right end and look for numeric digits
auto pos = path.length() - 1;
while ( pos > 0 && ( path[ pos ] ).isDigit() )
{
// Since we are reading in reverse order, we need to push front instead of back
digits.push_front( path[ pos ] );
pos--;
}
// Save the rest of the path minus the digits for building the new path
QString newPath
= path.
left( pos
);
// Build the new number suffix. Start with 1 as the first increment
int number = 1;
if ( !digits.isEmpty() )
{
// Convert the string to an int and increment it
number = digits.toInt() + 1;
}
// Convert it back to a string. Note: if you want something prettier, like "0001", "0002", etc.
// then use a field width and fill character: QString.arg( number, 4, '0' ). If you will have more
// than 10000 files, use a 5-digit field width and consider how badly you are filling up your
// customer's disk drive
// Now build the path again
newPath += digits; // add the new number
if ( !ext.isEmpty() ) // if the extensionis not empty add it along with the '.' separator
{
newPath += "."; // add the extension separator
newPath += ext; // add the extension
}
// and here's the new filename
return newPath;
)
I sure hope I didn't just give you the answer to your homework problem...