使用C语言检查raspberry pi 2中存在的文件

时间:2016-05-08 16:43:25

标签: c file raspberry-pi

我是C语言的新手并通过实验来学习。

我的挑战:我正在尝试验证文件“Command.txt”是否存在于raspberry pi中的文件夹中,然后我必须阅读该文件的内容。

我的代码:

#include <sys/stat.h>
#include <unistd.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <wiringPi.h>

// Pin number declarations. We're using the Broadcom chip pin numbers.
const int pwmPin = 18; // PWM LED - Broadcom pin 18, P1 pin 12
const int ledPin = 23; // Regular LED - Broadcom pin 23, P1 pin 16
const int butPin = 17; // Active-low button - Broadcom pin 17, P1 pin 11

const int pwmValue = 75; // Use this to set an LED brightness

int file_exist(char *filename)
{
  struct stat buffer;   
  return (stat(filename, &buffer) == 0);
}

int main(void) 
{
// Setup stuff:
wiringPiSetupGpio(); // Initialize wiringPi -- using Broadcom pin numbers

pinMode(pwmPin, PWM_OUTPUT); // Set PWM LED as PWM output
pinMode(ledPin, OUTPUT);     // Set regular LED as output
pinMode(butPin, INPUT);      // Set button as INPUT
pullUpDnControl(butPin, PUD_UP); // Enable pull-up resistor on button

printf("Blinker is running! Press CTRL+C to quit.\n");

while(1)
{
    FILE *command_file;
    char command[255];  

    while(file_exist("/home/pi/FTP/command.txt"))
    {
        command_file = fopen("/home/pi/FTP/command.txt", "r");
        fgets(command, 255, (FILE*)command_file);
        printf("1: %s\n", command );

        if(command == "First Light ON")
        {
            digitalWrite(ledPin, HIGH); //Change the raspberryPi pin state to 1
        }

        else if(command == "First Light OFF")
        {
            digitalWrite(ledPin, LOW); //Change the raspberryPi pin state to 0
        }

        else 
        {
            printf("Command is not yet defined");
        }

        fclose(command_file);
    }

    while(!(file_exist("/home/pi/FTP/command.txt")))
    {           
        printf("File does not exist\n");
        delay(1000); // Wait 1s again
    }
}


return 0;


}

当我在我的覆盆子pi中使用gcc命令运行此代码时,程序被执行但我只看到“文件不存在”消息,即使文件存在于给定文件夹中也是如此。

请帮我解释这个程序的逻辑。

0 个答案:

没有答案