简体   繁体   English

用C语言读写文件

[英]Reading and Writing to Files in C

I'm fairly new to C. This is the first program I've written involving reading and writing to files. 我是C的新手。这是我写的第一个涉及读写文件的程序。 So far, I was able to read the file, perform the operations I need but I am having trouble with 2 things. 到目前为止,我能够读取文件,执行我需要的操作,但我遇到了两件事情。

  1. Whatever the file is, it omits the last line when reading. 无论文件是什么,它都会在阅读时省略最后一行。 For example if the file has: 例如,如果文件具有:

     3 5 6 

    It will only read the 3 and 5 . 它只会读35 But if I leave an empty/blank line at the bottom it'll read all three. 但如果我在底部留下一个空/空行,它将会读取所有三行。 Any ideas as why that is? 任何想法为什么会这样?

  1. I now need to take what I did, essentially converting volts to milliVolts, microVolts, etc. and write it back to the file. 我现在需要采取我所做的,基本上将伏特转换为毫伏,微伏等,并将其写回文件。 What I have been doing up until now is reading it from the file and working through the console. 到目前为止我一直在做的是从文件中读取它并通过控制台进行操作。 So essentially, I want write the last two printf statements to the file. 基本上,我想将最后两个printf语句写入该文件。 I had some attempts at this but it wasn't working and I couldn't seem to find decent support online for this. 我有一些尝试,但它没有工作,我似乎无法在网上找到合适的支持。 When I tried, it would completely erase what was in the file before. 当我尝试时,它会完全删除之前文件中的内容。

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

int main(int argc, char** argv) {
    FILE * file = fopen ("bacon.txt", "r");
    float voltage = 0, voltageArray[100],  voltageToMilli = 0,voltageToMicro = 0, voltageToKilo = 0, voltageToMega = 0;
    int i = 1, j = 0;

    fscanf (file, "%f", &voltage);    
    while (!feof (file)) {
        printf("Line # %d\n", i);
        printf ("The voltage is: %f\n", voltage);
        voltageArray[j] = voltage;
        fscanf (file, "%f", &voltage); 

        printf("The voltage in Element %d is: %f Volts",j,voltageArray[j]);
        voltageToMilli = voltageArray[j] * 1000;
        voltageToMicro = voltageArray[j] * 1000000;
        voltageToKilo = voltageArray[j] * 0.001;
        voltageToMega = voltageArray[j] *0.000001;
        printf("\nThe voltage is %f Volts, which is: %f milliVolts, %f microVolts, %f kiloVolts, %f megaVolts",voltageArray[j],voltageToMilli,voltageToMicro,voltageToKilo,voltageToMega);


        printf("\n\n");
        i++;
        j++;



      }
    fclose (file);     

    return (0);
}

Please try to keep explanations clear and simple as I am a beginner in C. Thank you! 因为我是C的初学者,请尽量保持解释清晰简单。谢谢!

For the first issue, the problem is that the loop logic is incorrect. 对于第一个问题,问题是循环逻辑不正确。 On each iteration is stores the previous read data, reads the next data and then goes back to the top of the loop. 在每次迭代时,都会存储先前的读取数据,读取下一个数据,然后返回到循环的顶部。 The problem with this is that the next data is not stored until the next iteration. 这样做的问题是下一次迭代之前不会存储下一个数据。 But after reading the last data item (and before storing it into the array) the feof check is always false . 但是在读完最后一个数据项之后(以及在将其存储到数组中之前), feof检查始终为false Refer to this question for why checking feof as a loop condition is almost always wrong. 请参阅此问题,了解为什么将feof视为循环条件几乎总是错误的。

Here is an example of how you could restructure your code to read all the items as intended: 下面是一个示例,说明如何重构代码以按预期读取所有项目:

int rval;

while ((rval = fscanf(file, "%f", &voltage)) != EOF) {
    if (rval != 1) {
        printf("Unexpected input\n");
        exit(-1);
    }

    voltageArray[j] = voltage;

    /* Do the rest of your processing here. */    
}

problem is in the file there is nothing after the last number, so, after reading the last number from the file, feof(file) is true. 问题是在文件中最后一个数字后面没有任何内容,因此,在读取文件中的最后一个数字后,feof(file)为true。 and the while exits. 然后退出。

simplest fix is change it to this 最简单的解决方法就是改变它

while(fscanf (file, "%f", &voltage) == 1) {

and remove the other fscanf calls. 并删除其他fscanf调用。

this works because that fscanf() call will return 1 when it is able to read a number and either 0 or EOF (which is a negative number) otherwise. 这是有效的,因为fscanf()调用将在能够读取数字时返回1,否则返回0或EOF(这是负数)。

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

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