简体   繁体   English

用c读写文件

[英]Reading and writing files in c

i wanna know why my program can't input the numbers of my .txt file them into my array. 我想知道为什么我的程序无法将我的.txt文件的数字输入到数组中。 It reads them but i can't manage to input them into an array for later use. 它读取它们,但是我无法将它们输入到数组中以备后用。 Can anybody help me to understand better the management of reading and writing files in c, please i'm new at this topic, i know i'm supposed to use int instead of chars since my .txt file contains only numbers. 任何人都可以帮助我更好地理解在c中读写文件的管理吗,请问我是这个话题的新手,我知道我应该使用int代替chars,因为我的.txt文件仅包含数字。 But with the functions such as fgets is for chars only i think. 但是我认为fgets之类的功能仅适用于字符。

#include <stdio.h>

    int main()
    {
        FILE* file;
        char name[10] = "100.txt";
        char line[10];
        int n;
        char i[5];
        file = fopen(name, "rt");

        if (file == NULL)
        {
            printf("There is no such file!\n");
            return 0;
        }
        for (n=0; n < 100; n++){
        fgets(line, 5, file);
        //puts(line);
        i[n]=line;
        puts(i[n]);
        }
        fclose(file);

        return 0;
    }

if you switch to fscanf you can use int instead of char, and given that you are parsing a text file containing numbers it makes more sense. 如果切换到fscanf,则可以使用int代替char,并且鉴于您正在解析包含数字的文本文件,这样做更有意义。 Assuming your 100.txt has 100 number separated by a whitespace this should work: 假设您的100.txt包含100个数字,并用空格分隔,则应该可以使用:

int main(int argc, char* argv[])
{
    FILE* file;
    char name[10] = "100.txt";
    char line[10];
    int n;
    int numberArray[100];
    file = fopen(name, "rt");

    if (file == NULL)
    {
        printf("There is no such file!\n");
        return 0;
    }

    for (n=0; n < 100; n++){
        fscanf(file, "%d", &numberArray[n]);
    }
    fclose(file);

    return 0;
}

Here is the link for an explanation of fscanf . 这是fscanf解释的链接。

EDIT: 编辑:

There is another, and more elegant solution, to use fscanf: 还有另一个使用fscanf的解决方案:

while (fscanf(file,"%d",&numberArray[n++]) == 1);

in that way you loop through your text file as long as there are numbers (ie until EOF). 这样,只要有数字(即直到EOF),您就可以循环浏览文本文件。 Be careful as the program could crash if the count of numbers in the text file is greater than the space allocated for the array. 请注意,如果文本文件中的数字计数大于为数组分配的空间,则程序可能会崩溃

For writing back to a file: 要写回文件:

FILE* fp = fopen( "out_file.txt", "w" ); // Open file for writing
int arrNumSize = sizeof(numberArray) / sizeof(int);
for (int i = 0; i < arrNumSize; i++)
{ 
    fprintf(fp, "%d", numberArray[i] );
}

fclose(fp);

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

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