fopen using append on EXISTING files (malfunction) - c

Hi all I am relatively new to programming. Currently my code is working "correctly"
What I want to do is open a file for appending and then use couple different other source files to put data on the target file for appending.
The problem is that whenever I use fopen on the file name, it does not open the existing file but rather creates a file with no extension (all the files are in the same directory so should be able to open no problem). This is the code I am using to grab the necessary information for which file to append (error is never generated because it just creates a new file)
FILE *fp_target;
char target[100];
fgets(target, 99, stdin);
if ((fp_target = fopen(target, "a"))==NULL)
{
fprintf(stderr, "the following target file %s can not be appended", target);
exit (0);
}
Actually I tried this test a couple times and when i do this again with the same name used in the first try (lets say I used test.c) the program will open the test.c(no extension rather than the file "test extension (.c)")
can anyone please let me know what I am doing incorrectly?
also, when I fopen a file for reading it will read the file with the extension

Try to remove the newline from the input. By using
target[strlen(target)-1]='\0';
strlen() is used to find the length of the string which is available in string.h header file.
strlen(target)-1 which is used to find the newline location \0 the null character is pasted so the new line is removed.
If you worked with that new line the file is created as test.c?.
In disk we cannot create a file with the already exist name. So the newline is act as one character and the file name is created as like a existing name.

The problem is with your fgets(target, 99, stdin); line. After giving input 'test.c' it takes some garbage values till the end of the array. so every time it creates a new file. Instaed of fgets use scanf to get the input from user.
scanf("%s",target);
if ((fp_target = fopen(target, "a"))==NULL)
{
fprintf(stderr, "the following target file %s can not be appended", target);
exit (0);
}
If you want to use fgets to read the input from the user, after the user input make it NULL.
fgets(target, 99, stdin);
target[strlen(target)-1]='\0';

Related

Reading a string from a file with C. Fopen with w+ mode is not working

I made a C program that reads a string from a .txt file, then it encrypts the string, and finally it writes the string in the same file.
The thing is that if I use fopen("D:\\Prueba.txt","w+"), the program doesn't work, it prints garbage like this )PHI N.
I've debugged and I know the error is there in that line, because if I use fopen("D:\\Prueba.txt","r+"), the program works, and it writes what it should.
But I want to use w+ because it will rewrite what the .txt file had. Why is w+ not working?
If you're opening with w+ to first read the content, that's not going to work. From C11:
w+: truncate to zero length or create text file for update.
What's probably happening is that you read data from the now empty file but don't correctly check that it worked. That would explain the weird "content" you see of )PHI N.
One solution is to open the file as with r, open another file with w, and transfer the contents, encrypting them as part of that process. Then close both, delete the original, and rename the new one to the original name. This will allow you to process arbitrarily-sized files since you process them a bit at a time.
If you don't want to use a temporary file, and you're sure you can store the entire content in memory, you could open it r+, get the content, the reopen it with a new mode, such as with:
FILE *readFh = fopen( "myfile.txt", "r+");
// Read in content, massage as needed.
FILE *writeFh = frepoen( NULL, "w+", readFh);
// Provided that worked, you should now have an empty file to write to.
// Write back your massaged data.

Append Random Text to File (C)

I'm trying to create a file inside a directory, then append some random text inside of the file.
My Code
char dirname[30];
sprintf(dirname, "myroom.%d", (int)getpid());
mkdir(dirname,0777);
char path[path_max+1];
snprintf(path1, PATH_MAX+1, "%s/file1.txt,dirname);
FILE *filedir1 = fopen(path1, "a+");
fclose(filedir1);
char *random_name = { "burger", "toast", "burrito", "noodles" };
int number = rand();
fputs(random_name[number], filedir1];
What I want
(Inside directory "dirname")
When I open file1.txt, I expect there will be either the word burrito, burger, toast, or noodles in the first line.
What I get
file1.txt still empty.
Questions
Anybody know what happen with my code? I saw from youtube video, to append some text into a file, all I need is the fputs command but it doesn't seem to work in my code. Is it because I'm using "a+" in fopen?
Any help will be highly appreciated. Thanks
I think that rand() is creating problem.use rand()%4 instead.
And you are closing the file using fclose() before putting random word. Use it at last.
After opening a file, you are close that file. After closing the file, you are not able to enter the text to that file.
FILE *filedir1 = fopen(path1, "a+");
fclose(filedir1);
Your problem is in this fclose line. You have to do this in after finishing the write operation in that file.
So, remove the fclose(filedir1) and put this line after writing the file.

Creating a file using fopen()

I am just creating a basic file handling program.
the code is this:
#include <stdio.h>
int main()
{
FILE *p;
p=fopen("D:\\TENLINES.TXT","r");
if(p==0)
{
printf("Error",);
}
fclose(p);
}
This is giving Error, I cannot create files tried reinstalling the compiler and using different locations and names for files but no success.
I am using Windows 7 and compiler is Dev C++ version 5
Change the mode argument in fopen(const char *filename, const char *mode) from:
p=fopen("D:\\TENLINES.TXT","r");//this will not _create_ a file
if(p==0) // ^
To this:
p=fopen("D:\\TENLINES.TXT","w");//this will create a file for writing.
if(p==NULL) // ^ //If the file already exists, it will write over
//existing data.
If you want to add content to an existing file, you can use "a+" for the open mode.
See fopen() (for more open modes, and additional information about the fopen family of functions)
According to tutorial, fopen returns NULL when error occurs. Therefore, you should check if p equals NULL.
Also, in printf("Error",);, omit the comma after string.
Yes you should open the file in write mode.
Which creates the file . Read mode is only to read content
or else you can use "r+" for both read and write.
You should be able to open the file, but you need to make it first. Make a txt document with the name res.txt. It should be able to write your result into the text document.
<?php
$result = $variable1 . $variable2 "=" .$res ."";
echo $result;
$myfile = fopen("res.txt", "a+") or die("nope");
fwrite($myfile, $result);
fclose($myfile)
?>
fopen()
Syntax:
FILE *fp;
fp=fopen(“data.txt”,”r”);
if(fp!=NULL){
//file operations
}
It is necessary to write FILE in the uppercase. The function fopen() will open a file “data.txt”
in read mode.
The fopen() performs the following important task.
It searches the disk for opening the file.
In case the file exists, it loads the file from the disk into memory. If the file is found with huge contents then it loads the file part by part.
If the file does not exist this function returns a NULL. NULL is a macro defined character in the header file “stdio.h”. This indicates that it is unable to open file. There may be following reasons for failure of fopen() functions.
a.When the file is in protected or hidden mode.
b.The file may be used by another program.
It locates a character pointer, which points the first cha
racter of the file. Whenever a file is
opened the character pointer points to the first character of the file

In C, how do I append to a file line but not the end of the file? [duplicate]

This question already has answers here:
Appending text information to a text file at a certain spot without overwriting old information (C)
(3 answers)
Closed 9 years ago.
I have usernames and tweets stored in a file the following format:
username1:message1:message2:...:messageN
username2:message1:message2:...:messageN
...
usernameN:message1:message2:...:messageN
In the case where the file has a line where the username == the username with a new message attached, I want to append :newMessage to a line as formatted above.
How do I do this with C (with cygwin if that matters)? Here's the code block I wrote that I'm having trouble with.
while(fgets(line, MAXBUFF, fp) != NULL){ // get each line of file
if (strncmp(line, tweetUsr, strlen(tweetUsr)) == 0){
usrFound = 1;
fprintf(filePointer, ":");
fprintf(filePointer, tweet);
break;
}
memset(&line[0], 0, sizeof(line)); //reset line array
}
What I expect to happen is for the message to be appended to the end of the line since filePointer should be pointing to the end of the current line, but what's actually happening is the message is being appended to the end of the file.
I tried this using r+ mode in fopen. what do I have to do in order to be able to append to the current line rather than the end of the file?
You can't insert data in the middle of a file. If you try to write, you'll be writing over data that's already there.
If you want to do this, you need to:
fseek to the position you want to write to
fread from that point to the end of the file into a buffer
fwrite what you want to inserted
fwrite the buffer you read out
Another alternative to Jonathon Reinhart's answer would be:
read from the actual file line by line
write to a temp file while adding new message of certain users
when done (successfully done) delete original file and rename/move the temp file to the original.
This approach will bring more performance (in the worst case where each user has a new message) if you are adding messages of multiple users at a time.
What you need is a structure that is more flexible than a sequential file. Use some form of database, and append the messages to the list of messages for the user.

is there any option to create an output text file in the name of the input file in c programm?

is there any option to generate an output text file as same as the input file name?
in C i got the file name using:
gets(file_name);
and open it through the:
f1=fopen(file_name,"r");
comment.how do i open the file without entering the format type?
for example for file100.txt i'd like to enter file100 to read the file.
and any option to get the output file as same name as the input file?
You can use
snprintf(new_filename, sizeof new_filename, "%s.%d", File_name, int_val);
For your problem with the file name, you can use e.g. sprintf:
char full_file_name[256];
sprintf(full_file_name, "%s.txt", file_name);
This is not recommended without some validation of the entered file name of course.
For your other problem, from the documentation of fopen:
r+ Open for reading and writing. The stream is positioned at the beginning
of the file.
w+ Open for reading and writing. The file is created if it does not exist,
otherwise it is truncated.
The stream is positioned at the beginning of the file.
a+ Open for reading and appending (writing at end of file). The file is
created if it does not exist.
The initial file position for reading is at the beginning of the file,
but output is always appended to the end of the file.
for creating output file with the same name, simply save your output content into some string. Then, close the file and open it again with write mode("w"). And then, write the content and close the file again.

Resources