使用C写入csv文件会导致问题

我正在使用C程序写入CSV文件,并且发生了一些奇怪的事情。

  • 如果我将光标放在最后一行的新行上(当我使用文本编辑器打开它时),它会留下一行然后写入。为此,我尝试使用回卷和SEEK_END(偏移量分别为0和-1)重新开始,但似乎没有
  • 上班。
  • 如果将光标设置在最后一行的最后,则可以正常工作。

这是代码

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "Project.h"

void WriteEmployeeData(employee empF){
    FILE *f;;
    f=fopen("employee.csv","a");
        // printf("%ld\n",ftell(f));
        printf("%d\n",fseek(f, 0, SEEK_END));
        // printf("%ld\n",ftell(f));
        fprintf(f,"%d,%s,%ld,%s,%d\n",empF.employee_id,empF.employee_name,empF.phno,empF.shift,empF.area_code);

    fclose(f);


}

int main(int argc, char const *argv[])
{   employee e[100];
    int len=0;
    ReadEmployeeData(e,&len);
    WriteEmployeeData(e[2]);
    // WriteEmployeeData(e[3]);


    /* code */
    return 0;
}

这是第一种情况的输出(当光标在新行中设置为文件的最后一行时)

Employee_ID,Employee_Name,Phone_number,Shift,Area_Code^M
10111,John Smith,9933432921,9:00-13:00,201301^M
10112,Robert ,3914323431,10:00-13:00,201304^M
10113,Will,8884923312,16:00-20:00,110006^M
10114,Rakesh,9090991023,12:00-16:00,110076^M
10115,Kumaar,8292231231,8:00-12:00,201103^M
10116,Arbind,7318341312,11:00-13:00,120331^M
10117,Saurabh,8887567456,12:00-17:30,110087^M
10118,Ram Kumar,1230232331,10:30-18:00,110011^M
10119,Shiv,3213233123,11:30-15:30,201893^M
10120,Lakshay,4355634545,13:00-19:00,121232^M
10121,Rohan,9990999701,11:45-15:00,8773911^M
10113,Will,8884923312,16:00-20:00,110006^M
10114,Rakesh,9090991023,12:00-16:00,110076^M
^M
10113,Will,8884923312,16:00-20:00,110006

我如何防止增加那条多余的线 当我在vim中打开此csv时,这就是我得到的。

评论
xsint
xsint

The problem is that the CSV file you try to write into, has \r\n (which stand for resp. carriage return CtrlM and new line or line feed CtrlJ) at the end of each line. It is probably a file coming from a MS operating system. You see it when you open the file with vim: the text editor displays ^M for showing that some lines are terminated only with \n (the last line you added) and others with \r\n. Why the letter M? Because \r (carriage return) is the same as CtrlM.

You try to write into this file with another logic, with only \n as ine separator. This would work if you convert first your "carriage return + line feed" CSV file into a "line feed" only CSV file, with an utility like dos2unix.

If you need to keep the CSV file as it is, remind to finish each line you write with \r\n instead of \n, and if you want to overwrite a blank line at the end of the file, seek back with 2 positions to overwrite both \n and \r.

点赞
评论