Text File:
line_1: abcdefg
override the first k chars to ttttt so that the new text file is:
line_1: tttttfg
I used fprintf
and when opening the .txt file I used w+
flag, however it will erase the whole .txt
file and not just override the first bytes_number
characters.
I tried many things that didn't seem to wok. Any hints would be thankful! Thanks in advance!
void my_write (char* path, int bytes_number, char* flag, char* data, int sockfd)
{
FILE* fp;
char* test;
int n, i;
char buffer[BUFFER_SIZE];
if (bytes_number > 1000 || bytes_number < 0)
{
write (sockfd, "Failure", strlen("Failure"));
return;
}
test = data;
if (strlen(test) < bytes_number)
{
write (sockfd, "Failure", strlen("Failure"));
return;
}
if (!strcmp(flag, "override"))
{
fp = fopen(path, "w+"); /* Open file with flag 'w' so that we overrun the data */
if (fp == NULL) { /* File doesn't exist, invalid path*/
write (sockfd, "Failure", strlen("Failure"));
return;
}
**i = fprintf (fp, "%.*s\n", bytes_number, data);**
if (i < 0)
write (sockfd, "Failure", strlen("Failure"));
else
write (sockfd, "Write Success", strlen("Write Success"));
}
else if (!strcmp(flag, "append"))
{
fp = fopen(path, "ab"); /* Open file with flag 'ab' so that we don't override data while writing */
if (fp == NULL) /* File doesn't exist, invalid path*/
write (sockfd, "Failure", strlen("Failure"));
i = fprintf (fp, "%.*s\n", bytes_number, data);
if (i < 0)
write (sockfd, "Failure", strlen("Failure"));
else
write (sockfd, "Write Success", strlen("Write Success"));
}
else {
write (sockfd, "Failure", strlen("Failure"));
}
fclose(fp);
}