简体   繁体   English

读取.txt文件,C

[英]reading a .txt file, C

I am trying to parse through a line a line of text from a .txt file and set it to a string. 我正在尝试通过一行解析.txt文件中的一行文本并将其设置为字符串。 It is parsing most of the lines, except for the first 4 characters. 它会解析除前4个字符以外的大多数行。 This is what I'm trying to parse: 这是我要解析的内容:

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

And this is my code: 这是我的代码:

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);

Your fscanf() call consumes the first word of the input. 您的fscanf()调用消耗了输入的第一个单词。 Remove that call. 删除该呼叫。

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

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

Why do you do fscanf when you are doing fgetc. 在执行fgetc时为什么要执行fscanf。 This fscanf increments the file pointer to the next word. 此fscanf将文件指针递增到下一个单词。 Remove the fscanf and execute your code with the mentioned changes. 删除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);
  }

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

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