简体   繁体   English

fscanf读取多个字符串

[英]fscanf reading multiple strings

So I am creating ac program that reads a query file filled with commands to execute on tables. 因此,我正在创建一个ac程序,该程序读取一个查询文件,其中填充了要在表上执行的命令。 So I used: 所以我用了:

char command[100];
while(1)
{
    fscanf(query, "%s", command);
    x=strcmp(command, "select");
    //continue with checking for other commands etc.
    //if the command is stop then the loop breaks
}

My question is when I call fscanf the first time, I know it will save the command into the command array. 我的问题是,当我第一次调用fscanf时,我知道它将把命令保存到命令数组中。 But should I make the string "empty", or null as a better way to put it? 但是我应该将字符串“ empty”还是null作为更好的放置方式? I'm not sure if it's necessary when working with strcmp or in general with overwriting arrays with fscanf. 我不确定在使用strcmp或通常使用fscanf覆盖数组时是否有必要。 Thank you! 谢谢!

You should not worry about something that is going to be overwritten. 您不必担心会被覆盖的内容。 You should only ( always ) worry about initializing it before using its value . 您只( 总是 )担心在使用它的之前对其进行初始化。 Because otherwise it is undefined behavior. 因为否则它是未定义的行为。

More importantly, you should always check the return value of functions operating on memory. 更重要的是,您应始终检查在内存上运行的函数的返回值。 You can never count on "that would work". 您永远都不能指望“会起作用”。 Because after some time you would get Segmentation Fault out of the blue and won't know how to fix it. 因为一段时间后,您会突然遇到细分错误 ,并且不知道如何解决。

In case you don't know how: 如果您不知道如何:

int check;

check = fscanf(query, "%s", command);
if(check == EOF)
    perror("fscanf");

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

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