简体   繁体   English

如何在C的csv文件的行尾写入新的字符串

[英]how to write new string in the end of the line in csv file by C

I am writing a C code which need to add the new information in the end of the line if the condition match. 我正在编写一个C代码,如果条件匹配,则需要在该行的末尾添加新信息。

    FILE *file = fopen(fileName, "r+");

    //read every line if line!=NULL
    while (fgets(line, LINE_SIZE, file)!= NULL){
        //split the line by sep
        split(line, ',', fields);       
        fprintf(file,",%d,%d,%d",D,F,G);
   }

It is the code I try to write the matched information. 这是我尝试编写匹配信息的代码。 However, it will write the information in the beginning of the line. 但是,它将在该行的开头写入信息。 Is that possible I can move the "file" pointer to the end of the line? 我可以将“文件”指针移到行尾吗?

Probably you need to follow couple more steps 可能您需要执行几个步骤

Open a temporary file along with existing file 与现有文件一起打开一个临时文件

FILE *file = fopen(fileName, "r");
FILE *tmpFile = fopen(tempFileName, "a+" );

get a line from existing file, trim Next line append your fields after comma, probably create comma separated string of extra fields 从现有文件中获取一行,修剪下一行在逗号后追加您的字段,可能会创建用逗号分隔的额外字段字符串

while (fgets(line, LINE_SIZE, file)!= NULL){

Remove New line and add your paremeters 删除新行并添加您的参数

    if( line[ strlen(line) - 1  ] == '\n' )
        line[ strlen(line) - 1  ] = '\0';

    fprintf(tmpFile,"%s,%s\n",line, your_field); // Write to temporary file
}

Delete old file unlink is probably useful 删除旧文件取消链接可能有用

man -a unlink

and then rename temp file to original file 然后将临时文件重命名为原始文件

man -a rename

There's no way of doing what you want. 无法做您想做的事。 You can't insert bytes in the middle of a file. 您不能在文件中间插入字节。

However, if you have spaces or something similar that allows bytes to be written into the file without overwriting data, you could accomplish something close to what you want. 但是,如果您有空格或类似内容允许将字节写入文件而不会覆盖数据,则可以完成接近所需的操作。 Say you have the lines 说你有台词

"1,2,3,            "
"4,5,6,            "

(note the space) you could insert text there. (请注意空格),您可以在此处插入文本。 I would use two file pointers: 我将使用两个文件指针:

  • get the position from read file pointer when the line starts 行开始时从读取文件指针获取位置
  • read the line using that file pointer 使用该文件指针读取行
  • add the number of bytes until the first space to the position 将字节数增加到第一个空格为止
  • seek on the other file pointer to this position 在另一个文件上寻找指向该位置的指针
  • write the new data and make sure there's enough space 写入新数据并确保有足够的空间

The first file pointer would be in "read" mode, the second in "write" mode and none in "truncate" because that would screw up your file. 第一个文件指针将处于“读取”模式,第二个文件指针将处于“写入”模式,而没有一个处于“截断”模式,因为这会破坏文件。

Or use a much better database format. 或者使用更好的数据库格式。 ;) ;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM