简体   繁体   中英

Standard (or convenient) method to read and write tabular data to a text file in c

This might sound rather awkward, but I want to ask if there is a commonly practiced way of storing tabular data in a text file to be read and written in C.

Like in python you can load a full text file nto an array by f.readlines then go through all the lines and split each line by a specific character or sequence of characters (delimiter).

How do you approach this problem in C?

Pretty much the same way you would in any other language. Pick a field separator (IE, tab character), open the text file for reading and parse each line.

Of course, in C it will never be as easy as it is in Python , but approaches are similar.

Whoa. I am a bit baffled by the other answers which make me feel like I'm on Mainframes.stackexchange.com instead of stackoverflow.com

Why don't you pick a modern data format like JSON or XML and follow best practices for the data format of your choice?

If you want a good JSON reader/writer for C, I've used Jansson , and it's very easy and fast.

If you want a good XML reader/writer for C, I've used miniXML and it's also easy and fast. Also has SAX *and * DOM support depending on how you want to read in the XML.

Obviously there are a wealth of other libraries available as well.

Please don't give the next guy to come along and support your program some wacky custom file format to deal with.

我发现getline()strtok()非常方便( getline是一个gnu扩展,在POSIX.1-2008中标准化)。

There's a handful of mechanisms, but there's a reason why scripting languages have become so popular over the least twenty years -- some of the tasks that seem simple in scripting languages are ponderous in C.

  • You could use flex and bison to write a parser for your tables. This really only works if the format is very well defined and "static". They're amazing tools that can do more than you might suspect, but it is very heavy machinery for what could be done simply with a split() in a scripting language.

  • You could read individual fields using getdelim(3) . However, this was only standardized with POSIX.1-2008, so this is far from ubiquitous. (Every Linux machine with glibc should have them.)

  • You could read lines with fgets(3) and discover the split locations using strchr(3) .

  • You could read lines with fgets(3) and use strtok(3) to tokenize strings.

  • You can use scanf(3) to perform input and scanning in one go; it seems from the questions here that scanf(3) is difficult to use correctly.

  • You could use character-at-a-time parsing approaches: read characters using getc(3) , inspect it, do something with it, iterate until no more characters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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