簡體   English   中英

將文本文件中的一行讀入c中的字符數組

[英]Reading a line from a text file into an array of characters in c

我正在嘗試從文本文件填充數組。 該數組位於以下結構中:

struct ISBN
{
    long value;
};
struct Author
{ 
    char authorName[60];
};
struct  Book
{
    char *bookTitle;
    struct Author bookAuthor;
    struct ISBN bookID;
};

我試圖編寫一個fillin函數,該函數采用Book類型的文件和結構,如下所示:

void fillin (FILE * file, struct Book * bk)
{
    bk->bookTitle =(char*) malloc(1000);
    size_t n = 0;
    int c;

    file=fopen("book.txt","r");

    while ((c = fgetc(file)) != '\n')
    {
        bk->bookTitle[n++] = (char) c;
    }

    bk->bookTitle[n] = '\0'; 

    fscanf(file,"%s", &bk->bookAuthor.authorName);
    fscanf(file,"%lld",&bk->bookID.value);

    //fscanf(file,"%s", &bk->bookTitle);
}

文件book.txt具有以下數據:

UNIX Network Programming
W. Richard Stevens
0131411551

問題是,它無法掃描數組,我想從文本文件填充bookTitle和autherName數組。

以下行是錯誤的:

fscanf(file,"%s", &bk->bookAuthor.authorName);

當您掃描字符串時,字符數組已經是一個指針,因此您無需獲取其地址(&)。 嘗試:

fscanf(file,"%s", bk->bookAuthor.authorName);

為了安全起見(如果是長字符串),可以使用以下功能:

char * fgets ( char * str, int num, FILE * stream );

因此:

fgets(bk->bookAuthor.authorName, 60, file);

如果該行太長,則該字符串的其余部分將不會被復制。如果執行此操作,則可能必須檢查該字符串是否尚未終止,並丟棄其余字符,直到換行為止。 (例如while ((c = fgetc(file)) != '\\n'); )。 \\ n字符被復制到其中,因此您必須找到並刪除它:

bk->bookAuthor.authorName[59] = 0; // make sure it is null-terminated
int last = strlen(bk->bookAuthor.authorName)-1;
if (bk->bookAuthor.authorName[last] == '\n') {
    bk->bookAuthor.authorName[last] = 0; // read whole line
}
else ; // terminated early

您還可以使用fscanf限制字符,並使用以下命令讀取空格:

char c;
scanf(file, "%60[^\n]%c", bk->bookAuthor.authorName, c);

if (c=='\n') {
    // we read the whole line
} else {
    // terminated early, c is the next character
    //if there are more characters, they are still in the buffer
}

要丟棄該行的其余部分,您可以執行以下操作

while (c != '\n' && c != EOF) c = fgetc(file);

暫無
暫無

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

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