简体   繁体   English

从文本文件中读取索引

[英]Reading indexes from a text file

Currently, I have some code that will read each line from a text file and print it in the console.目前,我有一些代码可以从文本文件中读取每一行并在控制台中打印出来。 (EG Bread 2.10, Milk 3.30) (EG 面包 2.10,牛奶 3.30)

How would I modify this only read the second index of each line(Bolded for clarity) (EG 2.10, 3.30 and 5.50) I'd then like to multiply those numbers by 0.1 and overwrite the same file.我将如何修改它只读取每行的第二个索引(为清楚起见加粗)(EG 2.10、3.30 和 5.50)然后我想将这些数字乘以 0.1 并覆盖同一个文件。

File Format文件格式

Bread 2.10面包2.10

Milk 3.30牛奶3.30

Fish 5.505.50

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int c;
    FILE *file;
    file = fopen("oText.txt", "r");
    if (file) {
        while ((c = getc(file)) != EOF){
            putchar(c);
        }
        fclose(file);
    }
}

In its very simplest form, you want to read each line into a character array (a buffer) and then locate the last space in the buffer, and output from the next character to the end of the line.在其最简单的形式中,您希望将每一行读入一个字符数组(缓冲区),然后定位缓冲区中的最后一个空格,以及从下一个字符到行尾的 output。 That will output the 2nd field in your case.在您的情况下,这将 output 成为第二个字段。

Rather than using character-oriented input functions like getchar() or fgetc() , line-oriented input functions like fgets() or POSIX getline() read an entire line at a time into a sufficiently sized buffer.不是使用像getchar()fgetc()这样的面向字符的输入函数,而是像fgets()或 POSIX getline()这样的面向行的输入函数一次将整行读取到足够大的缓冲区中。 (rule: don't skimp on buffer size!!) The line-oriented input function also read and include the '\n' at the end of each line in the buffer they fill. (规则:不要吝啬缓冲区大小!!)面向行的输入 function 也读取并在它们填充的缓冲区中包含每行末尾的'\n' Generally you will want to trim the trailing '\n' from any string you are storing -- but you can also use it to your advantage to provide the '\n' if all you are doing is outputting the values as soon as they are read.通常,您将希望从您存储的任何字符串中修剪尾随'\n' - 但如果您所做的只是尽快输出值,您也可以利用它来提供'\n'读。

To find the last ' ' (space) in your buffer, the strrchr (string char reverse) function (provided in string.h ) will return a pointer to the last character you specify (or NULL if that character is not found in the buffer) This makes your job very easy.要查找缓冲区中的最后一个' ' (空格), strrchr (字符串字符反转)function(在string.h中提供)将返回指向您指定的最后一个字符的指针(如果在缓冲区中找不到该字符,则返回NULL ) 这使您的工作变得非常轻松。 Just read each line into a buffer, then call strrchr (buf, ' ') to obtain a pointer to the last space in your buffer, then simply print from the next character to the end of line.只需将每一行读入缓冲区,然后调用strrchr (buf, ' ')以获取指向缓冲区中最后一个空间的指针,然后简单地从下一个字符打印到行尾。

Reading from stdin (which you can simply redirect your file on stdin ), your code reduces to:stdin读取(您可以简单地将文件重定向到stdin ),您的代码减少为:

#include <stdio.h>
#include <string.h>

#define MAXC 1024   /* if you need a constant, #define one (or more) */

int main (void) {

    char buf[MAXC];     /* buffer (array of char) to hold line */

    while (fgets (buf, MAXC, stdin)) {          /* read each line */
        char *lastspace = strrchr (buf, ' ');   /* locate last space */
        if (lastspace != NULL)                  /* if space located */
            fputs (++lastspace, stdout);        /* output from next char on */
    }
}

( note: how fputs is used to output the line relying on the '\n' that was read and included in buf by fgets ) 注意: fputs如何用于 output 依赖于fgets读取并包含在buf中的'\n'的行)

Example Input File示例输入文件

Not knowing whether you had blank lines in your input file as shown, they were left in place (and note: they are gracefully skipped as strrchr will return NULL when the only thing in buf is the '\n' )不知道您的输入文件中是否有如图所示的空白行,它们被保留在原处(注意:它们被优雅地跳过,因为strrchr将返回NULLbuf中唯一的东西是'\n'

$ cat dat/breadmilk.txt
Bread 2.10

Milk 3.30

Fish 5.50

Example Use/Output示例使用/输出

Running the code above with the file contents passed in on stdin results in the following:使用在stdin入的文件内容运行上面的代码会产生以下结果:

$ ./bin/breadmilkcost < dat/breadmilk.txt
2.10
3.30
5.50

A Flexible Approach灵活的方法

Also note that because your are locating the last space in the file instead of just trying to read the second word, etc.., this method would work equally well and have the same output even if your file contained:另请注意,由于您正在查找文件中的最后一个空格,而不是仅仅尝试读取第二个单词等,因此即使您的文件包含以下内容,此方法也同样有效并且具有相同的 output:

Bread (two loaves) - 2.10

Milk (one carton) - 3.30

Fish (Alaskan Sockeye) - 5.50

Look things over and look up the man pages for fgets() and strrchr() to make sure you understand how things are working.仔细查看并查找fgets()strrchr()的手册页,以确保您了解事情是如何工作的。 If you have continuing questions, just drop a comment below and I'm happy to help further.如果您还有其他问题,请在下面发表评论,我很乐意为您提供进一步的帮助。

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

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