Append Random Text to File (C) - 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.

Related

Searching in a .map file with C

i want to create a tool which is able to search for a specific word in a .map file.
The word i am searchin for is ".text". I have loaded the file with
input_file = fopen("file_location","r") in read mode.
Now i am trying to search in this file for the string .text. My file has over 200 lines.
I would really appreciate some help from your side to solve this problem, because if(input_file == ".text") is not working.
my next solution would be to check every line for a match, but i dont know how i can load a complete line of a file into an array ?
Thanks a lot
Use fgets() to read the whole line and see whether your word is there in that line using strstr() perform the same operation till you read the whole file.
char buf[100];
while(fgets(buf,sizeof(buf),input_file) != NULL)
{
if(strstr(buf,".text"))
printf("Word found in the file\n");
}

fopen using append on EXISTING files (malfunction)

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';

query regarding writing in a file using c

Assume that the files are .txt
Contents of first file
hello how are you
Contents of second file
I am fine
The desired result is
hello how are you I am fine
Normally what happens is that the original contents are removed and then new contents are added in it.
I want to write in the first file in such a way that its original contents are maintained and the contents of second file are concatenated in it.
Is there any way to do that?
you can append another string in file by opening it in appending mode.
FILE *fp;
fp=fopen("file.txt","a");
here the next string will append after the last pointer of file.For more info link.
Yes, you can open the file with:
fopen("fileName", "a");
This will let you append to the end if the file.
More info is here: http://www.cplusplus.com/reference/cstdio/fopen/
It would help to know how you are trying to write the file. Likely, you are looking for the append option to FOPEN:
http://www.cplusplus.com/reference/cstdio/fopen/
FILE *f = fopen("foo.txt","a");
if (f != NULL) {
/* Use f */
fclose(f);
}

Where is a file placed when it is created like this?

How can I see where the file is created and open it?
#include <stdio.h>
int main ()
{
FILE * pFile;
char sentence [256];
printf ("Enter sentence to append: ");
fgets (sentence,255,stdin);
pFile = fopen ("mylog.txt","w");
fputs (sentence,pFile);
fclose (pFile);
return 0;
}
The file will be created in your current working directory.
Should find it in the directory you run the app from
The file will be create in the same directory the executable program is in.
you can open the same way you create it, changing the options to the fopen,,
FILE *inp;
inp = fopen("FileName","r");
// Do what you want
fclose(inp);
File is created in the same directory as the source code/C File because here you're giving relative path. If you want to put the file somewhere else, you can try giving Full path instead of relative one.
The file should be automatically created in your working directory (where you run the program from). You can open it in any text editor to make sure it was written properly.
If you meant how do you open it in the code, change "w" to "r".

C: read in more than one file

Hey guys using POSIX API system calls read, write, open, etc. I can open, read, write to a file and copy its contents to an output file. How would I go about copying more than one file to an output file using related system calls only?
I currently have:
filein = open(argv[1],O_RDONLY,0);
to open one file.(which is argv1 but I'd like to know how to do argv2 and argv3 etc.)
I tried :
j=0;
filein = open(argv[j],O_RDONLY,0);
but that prints out contents of argv0 into my outputfile.
I am stuck on the next stage to do more than one file. (I also have an EOF loop so after 1 file it exits-How would I make this continue for the next file).
Please could you help me with how to approach the next stage? Thanks.
Background
argv[0] is the name of the program.
argv[1] is the 1st command line parameter.
argv[2] is the 2nd command line parameter.
etc.
So:
Start your loop at 1, instead of 0 (i.e., j=0 is incorrect).
Be sure to close the file immediately after reading it and before opening the next file.
Algorithm
Think about the algorithm before writing the code.
Set counter to the index of the first argument.
Open the file.
Assign a handle to the open file.
Read the file contents.
Write (if required) the file contents.
Close the file using the handle.
Increment the counter.
Loop until there are no more command line arguments.
Now you can write the code.
You might get bonus points if you include error handling. (What happens when the file is missing, is not readable, the file system is corrupt, or the machine has run out of memory or disk space?)
Concatenating Files
If you want to concatenate two file names to a third, you need to rethink the algorithm, and what you need. There is a difference between "read the first two files given on the command line and write them to the third file" and "append all the files given on the command line to the last file given."
Read Two, Write One
The algorithm:
Make sure that there are exactly three parameters.
Create a file handle variable for the third file (output).
Create a file handle variable for the first file (input).
Create a file handle variable for the second file (input).
Open the first file for reading.
Open the second file for reading.
Open the third file for writing.
Read the contents of the first file and write them to the third file.
Read the contents of the second file and write them to the third file.
Close the third file.
Close the second file.
Close the first file.
You will notice a lot of redundancy at this point.
Read N, Write One
This algorithm is a bit more challenging, but removes the redundancy.
Make sure there are at least two parameters.
Open the last file for writing.
Loop over every file name up to, but not including, the last file name given:
Open the input file for reading.
Write the contents of the file to the last file.
Close the input file.
Close the output file.
For this you will need to understand argc and its relationship with argv. In pseudo-code:
if number_of_arguments < 2 then
print "This program concatenates files; two or more file names are required."
exit
end
int outfile = open arguments[ number_of_arguments ] for writing
int j = 1
while j < number_of_arguments do
int infile = open arguments[ j ] for reading
string contents = read infile
write contents to outfile
close infile
increment j
end
close outfile
Tutorials
If you are having trouble with C syntax, search for tutorials. For example:
http://www.cprogramming.com/tutorial/c/lesson3.html
Use a loop to read all the files. Start at 1 to skip the current executing process which is located at argv[0].
for(int i = 1; i < argc; ++i)
{
int filein = open(argv[i],O_RDONLY,0);
// ... process file
close(filein)
}
argv[0] is the name of the program. argv[1] is the first then you pass on the command line.
Open your output file then each input file. read each input file into the output file then close them all and exit.
to open one file.(which is argv1 but I'd like to know how to do argv2 and argv3 etc.)
fopen(argv[2], ...)

Resources