No way to truncate a file


#1

Hi Jules,

I didn’t find way to truncate a file in the JUCE 1.5.3. Is there any plan for this useful feature? Thanks!

BTW, I noticed 2 years ago there was a post that mentioned it:
http://www.rawmaterialsoftware.com/viewtopic.php?f=2&t=2907&hilit=truncate+file


#2

Yeah, good request. Not sure why I haven’t added that before!

Anyone know the unix/win32 commands to do it? (just to save me looking it up!)


#3

I’m not familiar with UNIX, but on MAC/LINUX/Windows, here’re a snippet which might be helpful. As MAC uses BSD underground, I guess it also covers UNIX already. BTW, it’s from another master :slight_smile:

#if (PLATFORM == PLATFORM_WIN)
    if (_chsize(fileHandle, static_cast<long>(inSize)) == -1)
	{
        MAThrow_Literal(runtime_error,"ftruncate");
	}
#elif (PLATFORM == PLATFORM_LINUX) || (PLATFORM == PLATFORM_MAC)
	// FIXME: on PLATFORM_MAC this is passing a Carbon refnum to a POSIX file call, which is a layering violation. It may not work properly.
	if (ftruncate(fileHandle, inSize) == -1)
	{
		MAThrow_Literal(runtime_error,"ftruncate");
	}
#endif

fileHandle = GetFileHandle()
{
#if (PLATFORM == PLATFORM_WIN)
    int flags = (mMode & mode_Write ? _O_RDWR : _O_RDONLY) | 
    			(mMode & mode_Create ? _O_CREAT | 
    			(mMode & mode_Exclusive ? _O_EXCL : 0) : 0) | O_BINARY;
	int handle;
    errno_t result = _tsopen_s(&handle, mPathName, flags, _SH_DENYNO, _S_IREAD | _S_IWRITE);
	if (result == 0)
	{
            return handle;
	}
#elif (PLATFORM == PLATFORM_MAC)
	FSSpec	spec;
	Boolean isDirectory;
	OSStatus err = FSPathMakeFSSpec((UInt8*)mPathName.CStr(), &spec, &isDirectory);
	if ((mMode & mode_Create) && err == fnfErr)
		err = FSpCreate(&spec, 'CLv2', 'BINA', smSystemScript);
	if (!err) {
		Boolean isDir = false, wasAlias = false;
		err = ResolveAliasFile(&spec, true, &isDir, &wasAlias);
	}
	if (!err) {
		short ref = -1;
		err = FSpOpenDF(&spec, mMode & mode_Write ? fsRdWrPerm : fsRdPerm, &ref);
		if (!err)
		{
                    return ref;
		}
	}
}