简体   繁体   English

***使用fscanf从C中的文件读取,扫描并打印.txt文件中不存在的字符

[英]***Reading from file in C*** using fscanf, Scanning and printing a char that doesn't exist in .txt file

Hello Everyone and Thank You for clicking!(Hate being stuck) 大家好,谢谢点击!(讨厌卡住了)

I'm trying to fscanf a char value from one file to a variable in my struct. 我试图将一个文件的char值fscanf转换为struct中的变量。 When I scan I get a completely different letter than the one I'm trying to get. 扫描时,我收到的信件与我尝试收到的信件完全不同。 The problem is in my readfile function. 问题出在我的readfile函数中。 If I get past this problem I hope I can scan numbers that I'll need to do arithmetic with is possible. 如果我解决了这个问题,希望可以扫描可能需要进行算术运算的数字。 My professor is teaching us FCFS (pertaining to OS scheduling algorithms not a FCFS data structure queue lesson). 我的教授正在教我们FCFS(与OS调度算法有关,而不是FCFS数据结构队列课程)。 So the text files columns mean (PAS.txt): 因此,文本文件列的意思是(PAS.txt):

Process Name | 流程名称| Arrival Time | 到达时间| Service Time 服务时间

   A    0   3
   B    2   6
   C    4   4
   D    6   5
   E    8   2  

//Main.c
#include <stdio.h>
#include <time.h>
#include "lab8Func.h"


int main(int argc, const char * argv[]) {

struct FCFS process;

readFile(&process);

printf("%s",&process.jobList[0].processName)

 }

//lab8func.h
#ifndef lab8Func_h
#define lab8Func_h
struct Job
{
    char processName;
    int arrivalTime;
    int serviceTime;
    int TAT;
    int NTAT;

};

struct FCFS
{
    struct Job jobList[5];

};

void readFile(struct FCFS*);

#endif /* lab8Func_h */

#include <stdio.h>
#include "lab8Func.h"


void readFile(struct FCFS *process1)
{  
FILE *file;
char temp;
int tempAT;
int tempST;



if((file = fopen("/Users/Vin/desktop/PAS.txt","r")) == NULL)
printf("Error, File Not Open.");
else
 {


    for(int i=0 ; i < 1; i++)
     {

         temp = fscanf(file," %c", &temp);  // where I'm stuck..
         process1->jobList[i].processName = temp;


        }


    }

}

OUTPUT OUTPUT

bProgram ended with exit code: 0 

***lowercase b ?? ***小写b ?? How ? 怎么样 ? I'm looking for capital A!!***** 我正在寻找大写字母A!*****

Firstly, the return value of fscanf is the number of arguments successfully written (or EOF on failure). 首先,fscanf的返回值是成功写入的参数数量(或失败时返回EOF)。 So you are overwriting your temp variable. 因此,您将覆盖temp变量。

temp = fscanf(file," %c", &temp);

Secondly, this print statement is wrong: 其次,此打印语句是错误的:

printf("%s",&process.jobList[0].processName)

%s means to print a null terminated string and you are passing it a pointer to a char. %s表示打印以null结尾的字符串,并且您正在将其传递给char的指针。 They are both of type char * which is why it compiles, but they way you are calling can't be expected to work and may crash. 它们都属于char *类型,这就是为什么要编译的原因,但是它们不能像预期的那样起作用,并且可能崩溃。

printf("%c",process.jobList[0].processName)

Thirdly, you are forgetting to read all three columns inside your loop with fscanf. 第三,您忘记使用fscanf读取循环内的所有三列。

The following proposed code: 建议的代码如下:

  1. cleanly compiles 干净地编译
  2. cleans up after it self (in this case closes the input file 自我清除后(在这种情况下,关闭输入文件)
  3. checks for and handles errors 检查并处理错误
  4. outputs error messages to stderr rather than stdout 将错误消息输出到stderr而不是stdout
  5. exits when a problem is incountered 遇到问题时退出
  6. does not contain 'magic' numbers. 不包含“魔术”数字。 IE the hard coded '5' IE硬编码为“ 5”
  7. reads up to 5 lines from the input file, instead of just one line 从输入文件最多读取5行,而不是一行
  8. corrects the (several) syntax errors in the posted code 更正已发布代码中的(几个)语法错误
  9. preforms the desired functionality 执行所需的功能
  10. still uses fscanf() although a better call would be fgets() as that would eliminate the code block containing getc() 仍然使用fscanf()尽管更好的调用是fgets() ,因为它将消除包含getc()的代码块
  11. eliminates unneeded local variables 消除不必要的局部变量
  12. uses the correct signature for the main() function main()函数使用正确的签名
  13. documents why each header file is included 说明为什么包含每个头文件
  14. follows the axiom: only one statement per line and (at most) one variable declaration per statement. 遵循公理: 每行仅一个语句,每个语句(最多)一个变量声明。
  15. keeps variable declaration local to where it is being used. 将变量声明保留在使用它的地方。
  16. makes some effort to improve the 'meaning' of the passed variable to the function: readFile() 尽力改善传递给函数的变量的“含义”: readFile()

Caveat: I modified the code layout (for my convenience) to all be in a single file 警告:为了方便起见,我将代码布局修改为一个文件

and now the proposed code: 现在建议的代码:

#include <stdio.h>   // fopen(), fclose(), fscanf(), perror()
#include <stdlib.h>  // exit(), EXIT_FAILURE
//#include <time.h>
//#include "lab8Func.h"

//lab8func.h
#ifndef lab8Func_h
#define lab8Func_h

#define MAX_RECORDS 5

struct Job
{
    char processName;
    int  arrivalTime;
    int  serviceTime;
    int  TAT;
    int  NTAT;

};

struct FCFS
{
    struct Job jobList[ MAX_RECORDS ];
};

void readFile(struct FCFS*);

#endif /* lab8Func_h */



int main( void )
{
    struct FCFS jobs;

    readFile(&jobs);

    printf("%c", jobs.jobList[0].processName);
} // end function: main


void readFile(struct FCFS *jobs)
{
    FILE *file = NULL;

    if((file = fopen("/Users/Vin/desktop/PAS.txt","r")) == NULL)
    {
        perror( "fopen failed" );
        exit( EXIT_FAILURE );
    }

    // implied else, fopen successful

    for(int i=0 ; i < MAX_RECORDS; i++)
    {
        char temp;
        if( 1 != fscanf(file," %c", &temp ) )
        { // handle error and exit
             perror( "fscanf failed" );
             fclose( file );  // cleanup
             exit( EXIT_FAILURE );
        }

        // implied else, fscanf successful

        jobs->jobList[i].processName = temp;

        // finish inputting the current line from the file
        int ch;
        while( (ch = getc( file ) ) != EOF && '\n' != ch )
        {
            ;
        }
    }

    fclose( file );   // cleanup
}  // end function:  readFile

One thing should be kept in mind that you should always look at fscanf or scanf for checking if its returning true or false(any integer value or 0) ie it is reading in correct format or not, and then process further. 请记住一件事,您应该始终查看fscanfscanfchecking其返回的是true还是false(任何整数值或0),即它是否以正确的格式读取,然后进行进一步处理。

You need to modify your code in for loop of readFile function: 您需要在readFile函数的for循环中修改代码:

   if((check=fscanf(file," %c", &temp))>0) 
      process1->jobList[i].processName = temp;

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

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