#include <unistd.h>
|
|
int
truncate (const char *path, off_t length); |
|
int
ftruncate (int fd, off_t length); |
//example for truncate
#include<unistd.h>
#include<stdio.h>
#include <sys/stat.h>
int test_truncate()
{
int retVal, retVal2, retSize, retSize2;
struct stat buf;
ssize_t size;
char *buffer = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwx";
int fp = open("c:\test.txt", O_RDWR|O_CREAT);
size = write(fp,buffer,50);
close(fp);
retVal2 = stat("c:\test.txt", &buf );
if ( !retVal2 )
{
retSize = buf.st_size;
printf("Size before: %d", retSize);
retVal = truncate("c:\test.txt", retSize/2 );
}
else
{
printf("Failed");
}
retVal2 = stat( "c:\test.txt", &buf );
if ( !retVal2 )
{
retSize2 = buf.st_size;
if( retSize2 == (retSize/2 ) )
{
printf("\nSize after: %d\n", retSize2);
printf("Truncate passed");
return 0;
}
else
{
printf("Failed");
return -1;
}
}
else
{
printf("Failed");
return -1;
}
}
Output
Size before: 50
Size after: 25
Ttruncate Passed
//example for ftruncate
#include<unistd.h>
#include<stdio.h>
int test_ftruncate()
{
//assuming that the file exists and has some //data in it
int fp = open("c:\test.txt", O_RDWR);
int retVal, retVal2, retSize, retSize2;
struct stat buf;
if(fp != -1)
{
retVal2 = fstat( fp, &buf );
if ( !retVal2 )
{
retSize = buf.st_size;
printf("Size before: %d", retSize);
retVal = ftruncate( fp, retSize/2 );
close(fp);
}
else
{
printf("Failed");
}
fp = open("c:\test.txt", O_RDONLY);
if((fp != -1) && (!retVal))
{
retVal2 = fstat( fp, &buf );
if ( !retVal2 )
{
retSize2 = buf.st_size;
if( retSize2 == (retSize/2 ) )
{
printf("\nSize after: %d\n", retSize2);
printf("Ftruncate Passed");
}
else
{
printf("Failed");
}
}
else
{
printf("Failed");
}
}
}
Output
Size before: 100
Size after: 50
Ftruncate Passed
| [EBADF] | |
| The fd argument is not a valid descriptor for a regular file. | |
| [EINVAL] | |
| The fd argument references to an object other than a file. | |
| [EINVAL] | |
| The fd descriptor is not open for writing. | |
Use of truncate to extend a file is not portable.
|
© 2005-2007 Nokia |