简体   繁体   English

使用 fscanf() 从文件中读取文本

[英]Reading text from a file using fscanf()

guys i want to read the text from my file and assign every character to a single element of the array伙计们,我想从我的文件中读取文本并将每个字符分配给数组的单个元素

char A[1000];

FILE * fpointer;
fpointer=fopen("text.txt","r");

i=0;
while(!feof(fpointer))
{
    fscanf(fpointer,"%c",&A[i]);
    i=i+1;
}

fclose(fpointer);

for (i=0;i<100;i++)
{
    printf("%c",A[i]);
}

return 0;

but the problem is that the output is some weird symbols instead of the file's text which is "This is just a test".Why is that happening ?但问题是输出是一些奇怪的符号,而不是文件的文本,即“这只是一个测试”。为什么会这样?

Possible reasons include:可能的原因包括:

  1. fopen failed to open the specified file. fopen未能打开指定的文件。 Fix by checking the return value of fopen .通过检查fopen的返回值来修复。
  2. See Why is “while ( !feof (file) )” always wrong?请参阅为什么“while (!feof (file))”总是错误的?
  3. You always print 100 characters, but if the file contains less than 100 characters, you're in trouble because you print uninitialized locations of the array, leading to UB.你总是打印 100 个字符,但如果文件包含少于 100 个字符,你就会遇到麻烦,因为你打印了数组的未初始化位置,导致 UB。 Fix by printing everything starting from zero upto i .通过打印从零开始到i所有内容来修复。

Corrected code snippet:更正的代码片段:

int i = 0, j = 0;
char A[1000];

FILE* fpointer;
fpointer = fopen("text.txt", "r");
if(!fpointer)
{
    fputs("fopen failed! Exiting...\n", stderr);
    exit(-1); /* Requires `stdlib.h` */
}

while(fscanf(fpointer, "%c", &A[i]) != EOF)
{
    i = i + 1;
}

fclose(fpointer);
for (j = 0; j < i; j++){
    printf("A[%d] = '%c'\n", j, A[j]);
}

To expand on the points by @Cool Guy :要扩展@Cool Guy观点

In case your files do not contain the null character , you can avoid using another variable to store the number of characters read.如果您的文件不包含空字符,您可以避免使用另一个变量来存储读取的字符数。 If you null terminate your read in characters, you can just print them directly as a string.如果 null 终止读取字符,则可以直接将它们打印为字符串。

You have to make sure that A can hold enough characters.您必须确保 A 可以容纳足够的字符。 If you expect at most 1000 characters, make sure that A has a size of 1001 bytes to contain the terminating NUL character.如果您期望最多 1000 个字符,请确保 A 的大小为 1001 个字节以包含终止 NUL 字符。

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

int main(int argc, char **argv)
{
    char A[1001] = { 0 }; /* init to NUL, expect at most 1000 chars */
    int i;    
    FILE *fpointer;

    fpointer=fopen("text.txt","r");
    if(!fpointer) {
        perror("Error opening file"); /* print error message */
        exit(-1); /* Requires `stdlib.h` */
    }
    /* read all characters from fpointer into A */
    for (i=0; fscanf(fpointer, "%c", &A[i]) != EOF; i++);
    fclose(fpointer);

    printf("%s\n",A); /* print all characters as a string */

    /* alternatively, loop until NUL found */
    for (i=0; A[i]; i++)
        printf("%c", A[i]);
    printf("\n");

    return 0;
}

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

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