簡體   English   中英

如何在C中讀取文件並將字符存儲在變量中

[英]How do I read a file in C and store the characters in a variable

我對C完全陌生,因此急需幫助。 我用fopen()讀取文件,然后使用fgetc()獲取文件內容。 我想知道的是如何訪問fgetc()返回的行,以便將第4個至第8個字符放入char數組中。 下面是我在網上找到的示例,但是在解析數據返回值時遇到了困難,我仍然對C缺乏深刻的了解,也沒有獲得如何使用int來存儲一行字符的方法。

    FILE *fr;
fr = fopen("elapsed.txt", "r");
int n = fgetc(fr);
    while(n!= EOF){
        printf("%c", n);
        n = fgetc(fr);
    }   printf("\n");

在這里1首先打開文件2獲得文件的大小3為字符指針4分配大小,並從文件中讀取數據

FILE *fr;
char *message;
fr = fopen("elapsed.txt", "r");
/*create variable of stat*/
struct stat stp = { 0 };
/*These functions return information about a file. No permissions are required on the file itself*/
stat("elapsed.txt", &stp);
/*determine the size of data which is in file*/
int filesize = stp.st_size;
/*allocates the address to the message pointer and allocates memory*/
message = (char *) malloc(sizeof(char) * filesize);
if (fread(message, 1, filesize - 1, fr) == -1) {
    printf("\nerror in reading\n");
    /**close the read file*/
    fclose(fr);
    /*free input string*/
    free(message);
}
printf("\n\tEntered Message for Encode is = %s", message);

PS不要忘記添加#include <sys/stat.h>

您沒有使用fgetc檢索行。 您一次從文件中檢索一個字符。 該示例將不斷檢索字符,直到遇到EOF字符(文件末尾)為止。 看一下對fgetc的描述。

http://www.cplusplus.com/reference/clibrary/cstdio/fgetc/

在while循環的每次迭代中,fgetc都將檢索一個字符並將其放入變量“ n”。 可以幫助您使用C語言中的“字符”的東西只是將其視為一個字節,而不是實際字符。 您在這里不了解的是,int是4個字節,字符是1個字節,但是兩個都可以為相同的ASCII字符存儲相同的位模式。 唯一的不同是內部變量的大小。

上面的示例顯示帶有“%c”的printf,這意味着將“ n”中的值當作ASCII字符對待。

http://www.cplusplus.com/reference/clibrary/cstdio/printf/

您可以在while循環中使用計數器來跟蹤您的位置,以從文件中找到第4個和第8個值。 您還應該考慮如果輸入文件小於最大大小會發生什么。

希望能有所幫助。

好吧,請看一下它的盒子尺寸,我可以有一個30厘米x 30厘米的盒子,可以容納1個泡沫字母。 現在我正在調用的函數“可以”返回一個60cm x 60cm的字母,但它有99%的可能性返回30cm x 30cm的字母,因為我知道它的讀數-我知道是否給它一個60cm x 60cm的盒子永遠不會感到意外。

但是,如果我確定結果始終是30cm x 30cm的盒子,那么我知道我可以轉換返回60cm x 60cm盒子的函數的結果而不會丟失任何東西

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM