Reputation: 631
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);
}
Upvotes: 1
Views: 1598
Reputation: 41046
The string pointed to by argv[0]
represents the program name, so you are receiving 3 arguments: changefilesize
, data.txt
and 100
.
and here
FILE *file = fopen(argv[0], "r");
int ftruncate(int file, off_t length);
fclose(file);
the second line is a prototype (not a call to ftruncate
) change to
FILE *file = fopen(argv[1], "w"); /* 1 instead of 0 and "w" instead of "r" */
ftruncate(fileno(file), 100);
fclose(file);
Note that with ftruncate
the file must be writable.
Upvotes: 2
Reputation: 843
The first argument of your program is its name (in argv[0]). So if you give 2 arguments, argc
is 3 (path + 2 arguments).
See this question for more details.
Upvotes: 1