I am trying to make a C program that changes the size of input file to desired size by truncating or extending the input file using ftruncate. It must also use command line arguments.
For example, the following is valid input:
./changefilesize data.txt 100
If the size of data.txt = 100, then return save file, if more than 100 then cut off the end, if less than 100, then extend the file size to 100.
I am having trouble dealing with input arguments and using ftruncate. The only information I found about ftruncate is basically the man
info which says:
#include <unistd.h>
int ftruncate(int fildes, off_t length);
int truncate(const char *path, off_t length);
Here is what I have so far:
#include <stdio.h>
#include <unistd.h>
int main (int argc, char *argv[]) {
if ( argc != 2 ) {
printf("2 inputs expected\n");
}
else {
int length;
length = atoi (argv[1]);
FILE *file = fopen(argv[0], "r");
int ftruncate(int file, off_t length);
fclose(file);
}
}
If I enter ./changefilesize data.txt 100
, I get 2 inputs expected
and I don't understand why.
Edit: updated code based on answers:
#include <stdio.h>
#include <unistd.h>
int main (int argc, char *argv[]) {
long length;
length = atoi (argv[2]);
FILE *file = fopen(argv[1], "w");
ftruncate (fileno(file), length);
fclose(file);
}