Click here to Skip to main content
15,901,205 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to delete a line in csv(comma separated values)
but I cant find how to do it...
All I find is how to display the records of course without the comma...

Hope anyone can help....

Thanks...
Posted

A CSV file is not a structured file like a database. So 'deleting' a line really involves copying all the lines, up to the line you want to delete, skipping that line, and writing the rest of the file.
Note that you'll find database ODBC drivers for csv files, which let you 'delete' complete rows, but under the hood, they'll just re-write the file.

Note that, given current memory sizes, you'll be better off loading the entire file in a linked list, doing all your operations in memory on the linked list, and then writing out your new file...
 
Share this answer
 
Yeah I do not in other language like python and java but in C its so hard to overwrite the existing file because you must read it and same time append line to it

Sample...

File *file1;
file1 = fopen("data.csv","r");


without closing the file1 I cannot create...

File *file2;
file2 = fopen("data.csv","a+");


when I do the above code without closing the file1 the error occur.
 
Share this answer
 
Please don't push answer to write questions. Yes, if your file is already open, you can't reopen it. You need to read the data, close it, open it for writing and overwrite it.
 
Share this answer
 
What you normally do is:
Open the original file in R/W, exclusive. Ask the OS for a temp file in the same directory. Write to that one.
Rename the original file to a .bak extension, or whatever takes your fancy. Don't worry, you can rename the file while it's open exclusive to you.
Rename the temp file to the original name.
Close and delete the original file.

This way, if anything fails, you always have a back copy handy.
 
Share this answer
 
I remember, this question was posted on comp.lang.c long time ago and the suggestion was (if you don't want do write to a temporary file):
Instead of actually deleting records, you might consider just marking them as deleted, and having the code which reads the file ignore them. (You could run a separate coalescion program once in a while to rewrite the file, finally discarding the deleted records. Or, if the records are all the same length, you could take the last record and use it to overwrite the record to be deleted, then truncate the file.
 
Share this answer
 
You're using C ? Not C# or C++ ?

You can't do it. You have to read in the whole file, then overwrite the existing file with a new file that has the data minus the line.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900