读取.text文件,C

时间:2014-03-12 22:38:26

标签: c parsing

我正在尝试从.txt文件中解析一行文本并将其设置为字符串。它解析大多数行,除了前4个字符。这就是我要解析的内容:

  

12X6 de8 dw3 ds5 g8,7 m3,4 p2,2 h2,2

这是我的代码:

FILE * rooms;
int i;
char c;
char roomString[ROOM_STRING_LENGTH];    
rooms = fopen("assets/rooms.txt", "r");

if(rooms == NULL)
{
    printf("error opening file\n");
}

fscanf(rooms, "%s", roomString);
while((c=fgetc(rooms))!='\n')
{           
    roomString[i] = c;
    i++;
}
printf("%s\n", roomString);

2 个答案:

答案 0 :(得分:1)

您的fscanf()来电会消耗输入的第一个字。删除该电话。

if(rooms == NULL)
{
    printf("error opening file\n");
}

//fscanf(rooms, "%s", roomString);
while((c=fgetc(rooms))!='\n')

答案 1 :(得分:1)

为什么在做fgetc时会做fscanf。此fscanf将文件指针递增到下一个单词。删除fscanf并使用上述更改执行代码。

   #include<stdio.h>

   #define ROOM_STRING_LENGTH 50
    void main(){

    FILE* rooms;
    int i =0;
     char c;
     char roomString[ROOM_STRING_LENGTH];    
     rooms = fopen("rooms.txt", "r");
     if(rooms == NULL)
     {
        printf("error opening file\n");
      }

     //fscanf(rooms, "%s", roomString);
      //printf("%s\n", roomString);
     while((c=fgetc(rooms))!='\n')
     {

        roomString[i] = c;
         i++;
     }
     roomString[i] ='\0';
     printf("%s\n", roomString);
  }