int main(int argc, char *argv[]) {
int fd_src = open(argv[1], O_RDWR);
ssize_t size = lseek(fd_src, 0, SEEK_END);
char *buf[size];
char *prefix = strcat(argv[1], "_");
for(int i = 0; i < size-1; i ) {
lseek(fd_src, i, SEEK_SET);
read(fd_src, buf, 1);
char *postfix = &buf[0];
char *filename = strcat(prefix, postfix);
int fd_dest = open(filename, O_RDWR | O_CREAT | O_EXCL, 0644);
write(fd_dest, buf, 1);
close(fd_dest);
}
close(fd_src);
return 0;
}
The input-file "filename" only contains the string "abc"
After I run the program, the output looks like that:
filename_a // file contains a filename_ab // file contains b filename_abc // file contains c
But I would like it to look like that:
filename_a // file contains a filename_b // file contains b filename_c // file contains c
I have already tried to declare the postfix like that:
char *postfix = &buf[i]
But that didn't work either. Any suggestions? :)
CodePudding user response:
char *prefix = strcat(argv[1], "_");
it is wrong as you attach one character to the string kept in the argv[1] and argv[1] is very unlikely to be big enough to accommodate it. It is very likely undefined behaviour.
From your code, I understand that you want to append the file name the first character of the file content.
char filename[strlen(argv[1] 3];
/* ... */
sprintf(filename, "%s_%c", argv[1], buf[0]); // you need to change the type of buf
char *buf[size];
it is an array of pointers not characters. It will work as sizeof(char *) is always > sizeof(char)
, but you need an array of characters.
char buf[size];