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], ...)
Related
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.
I wrote this code to input a number from a user and output it to a file .But its is not working ,after running the code the output.txt file is still empty.
Please tell me where I have done wrong .
I assure that I have created the output.txt file before running the program so the
file pointer will not be NULL.
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
FILE *ptr;ptr=fopen("output.txt","rw");
if(ptr==NULL){printf("Error in oppening file aborting .......");exit(0);}
char ch[100];
scanf("%s",ch);
fprintf(ptr,"%s",ch);
fclose(ptr);
return 0;
}
From fopen documentation, the supported access modes are:
"r" read: Open file for input operations. The file must exist.
"w" write: Create an empty file for output operations. If a file with
the same name already exists, its contents are discarded and the file
is treated as a new empty file.
"a" append: Open file for output at the end of a file. Output
operations always write data at the end of the file, expanding it.
Repositioning operations (fseek, fsetpos, rewind) are ignored. The
file is created if it does not exist. "r+" read/update: Open a file
for update (both for input and output). The file must exist.
"w+" write/update: Create an empty file and open it for update (both
for input and output). If a file with the same name already exists its
contents are discarded and the file is treated as a new empty file.
"a+" append/update: Open a file for update (both for input and output)
with all output operations writing data at the end of the file.
Repositioning operations (fseek, fsetpos, rewind) affects the next
input operations, but output operations move the position back to the
end of file. The file is created if it does not exist.
In your code you use "rw" which is invalid and that's the reason your program doesn't work.
Change "rw" to "w" and your program will work. Note that you don't need to create output.txt, fopen will create it for you if your current user has write privileges in program's directory.
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.
I would like to know how the contents of a file can be cleared in *nix if it is open to write. (It may be a log file for example.)
Take a look at fopen's manpage:
w
Truncate file to zero length or create text file for writing. The stream is positioned at the beginning of the file.
so if you use
fp=fopen("file.txt", "w");
the contents of file.txt will be erased.
Update:
To delete a file's contents from command line use
printf "\0" > file.txt
FILE *ExcelFile = fopen("testdata.csv","w");
if (ExcelFile == NULL)
return -1;
fprintf(ExcelFile,"1 2 3");
fprintf(ExcelFile,"\n");
fclose(ExcelFile);
//==============================================
FILE *fa = fopen("testdata.csv","w");
if (fa == NULL)
return -1;
fseek (fa, 6 , SEEK_SET );
fprintf(ExcelFile,"a");
fclose(fa);
in the code i have write 1 2 3 in the file and also inserted '\n' (required for the program) now i want to place a after 3 like 1 2 3 a but hte problem iam facing is that my code erase all char an simply write a . help required .thanks
First of all, a CSV file should have "comma separated values", as the name indicates. So, rather than "1 2 3", you'd better have "1,2,3" or "1;2;3".
Now, there are multiple ways of opening a file : you're only using the "w" as "writing" mode. When you're in writing mode, you're erasing your file. You could use the "a" as "add" mode, which mean that everything will be put after it.
You could also :
1°) First read your file with a "r" mode and store it in memory. Then, close it.
2°) Then, open your file with a "w" mode, copy what you stored, and then make your addendum. Then, close it.
(There is a "reading and writing mode" too, check the link provided by another answer ; but this solution can easily be broken in small pieces, to have small functions doing each their part of the job).
Every time you open your file, you are opening it as a 'w' option. In C, this has a specific meaning : start writing at the beginning of the file.
For your first write of the file, this is okay, but for every subsequent write, you're overwriting your previous content.
Solution Use the 'a' attribute instead here. Like this:
FILE *fa = fopen("testdata.csv","a");
See more information about fopen here...
EDIT
Reading your comments, I understand that when you write again, the next thing starts on a new line. This is because of your initial write 1 2 3 \n (The \n makes a new line).
To correct this you can :
Don't write a '\n' at all.
OR
Read the entire file first, rewrite it without the \n and then write your new a and \n
You want mode "r+". Using mode "a", all writes will go to the end of the file.
You specified w for fopen(), which means "create the file or open for overwrite if already exists".
Therefore, your second call to fopen() cleared the file's contents.
Use a, for: "create the file, or append to it if already exists".
fopen (filename,"a")
a = append