problem writing in file - c

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

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.

Read/Write highscore from a file (Lua - Corona SDK)

Here's my issue: I have a file with the highscore written in it (just the first line, no nicknames, just the highscore), I need to read that line and compare it with the actual score obtained in the game session, if the score is higher, overwrite the file with the new value, but if I try to read it I get a null value... Seems like i'm not reading it the right way. What's wrong with my code?
Thanks for the help!
local path = system.pathForFile( "data.sav", system.DocumentsDirectory )
local file = io.open( path, "w+" )
highscore_letta = file:read("*n")
print(highscore_letta)
if (_G.player_score > tonumber(highscore_letta)) then
file:write(_G.player_score)
end
io.close( file )
I had this problem myself. I found out that if you open a file in "w+" mode, the current contents are deleted, so that you can write new contents. So to read and write you have to open the file twice. First, you open the file in "rb" mode and get the file contents, then close it. Then you reopen it in "wb" mode, write the new number, and close it.
In Windows, you need "b" in the file mode. Otherwise, the strings that you are reading and writing may be modified in unexpected ways: for instance, a newline ("\n") may be replaced with carriage return–newline ("\r\n").
The file modes that Lua supports are borrowed from the C language. (I found a description on page 305 of what I guess is a draft of the C specification.) I think the Lua manual sort of assumes that you will know what these modes mean, as an experienced C programmer would, but to me it wasn't at all obvious.
Thus to read a number and then write a new one:
local filepath = "path/to/file"
-- Create a file handle that will allow you to read the current contents.
local read_file = io.open(filepath, "rb")
number = read_file:read "*n" -- Read one number. In Lua 5.3, use "n"; the asterisk is not needed.
read_file:close() -- Close the file handle.
local new_number = 0 -- Replace this with the number you actually want to write.
-- Create a file handle that allows you to write new contents to the file,
-- while deleting the current contents.
write_file = io.open(filepath, "wb")
write_file:write(new_number) -- Overwrite the entire contents of the file.
write_file:flush() -- Make sure the new contents are actually saved.
write_file:close() -- Close the file handle.
I created a script to do these operations automatically, as they're somewhat annoying to type every time.
The mode "r+" or "r+b" is supposed to allow you to read and write, but I couldn't get it to work when the original contents are longer than the new contents. If the original contents are "abcd", four bytes, and the new contents are "efg", three bytes, and you write at offset 0 in the file, the file will now have "efgd": the last byte of the original contents is not deleted.

How to properly append lines to already existing file

I looked over the internet trying to find a solution for writing line by line into a file in c. I found solutions like changing the mode of fopen() to w+, wt, wb but it did not work for me. I even read to put \r instead of \n in the end of the line but still when I try to write to the file the only thing that is written there is the last line.
FILE *log = NULL;
log = fopen(fileName, "w");
if (log == NULL)
{
printf("Error! can't open log file.");
return -1;
}
fprintf(log, "you bought %s\n", pro[item].name);
fclose(log);
Many thanks for your time and help.
It is because everytime you execute fprintf in "w" mode, the log gets overwritten with the new contents as the file was not opened in the 'append' mode but in 'write' mode.
Better thing would be to use:
fopen("filename", "a");
If I understood your problem correctly, you can have two approaches,
Case 1 (Opening / closing multiple times, write one value at a time)
You need to open the file in append mode to preserve the previous content. Check the man page of fopen() for a or append mode.
Case 2 (Opening / Closing once, writing all the values at a stretch)
you need to put the fprintf() statement in some kind of loop to get all the elements printed, i.e., the index (item) value goes from 0 to some max value.

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], ...)

Inserting data to file in c

I need to add a string before the 45th byte in an existing file. I tried using fseek as shown below.
int main()
{
FILE *fp;
char str[] = "test";
fp = fopen(FILEPATH,"a");
fseek(fp,-45, SEEK_END);
fprintf(fp,"%s",str);
fclose(fp);
return(0);
}
I expected that this code will add "test" before the 45th char from EOF, instead, it just appends "test" to the EOF.
Please help me to find the solution.
This is continuation of my previous question
Append item to a file before last line in c
Open it with mode r+ (if it already exists) or a+ (if it doesn't exist and you want to create it). Since you're seeking to 45 bytes before the end of file, I'm assuming it already exists.
fp = fopen(FILEPATH,"r+");
The rest of your code is fine. Also note that this will not insert the text, but will overwrite whatever is currently at that position in the file.
ie, if your file looks like this:
xxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxx
Then after running this code, it will look like this:
xxxxxxxtestxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxx
If you really want to insert and not overwrite, then you need to read all the text from SEEK_END-45 to EOF into memory, write test and then write the text back
Don't open it as append (a) if you plan to write at arbitrary positions; it will force all writes to the end of the file. You can use r+ to read or write anywhere.
To avoid platform-specific configurations, always explicitely indicate the binary or text mode in your fopen() call.
This will save you hours of desperations if you port your code one day.

Resources