使用 open 读取仅使用一个值的文本文件并尝试锁定该文件

Read a text file using with only a value using open and try to lock the file

我有一个文本文件,如“~/MA14.txt”,只有一个值 0 或 1。我需要用系统调用打开打开文本文件,(最终锁定文件直到我阅读)并检查该值是 0 还是 1。我正在使用 0.

的文件测试函数

问题是函数 returns 48(ascii 值为零)而不是 0。

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <fcntl.h>
#include <string.h>


int get_permission(char *file_path_name);

int main() {
    char cwd[1024];
    if (getcwd(cwd, sizeof(cwd)) != NULL)
        fprintf(stdout, "Current working dir: %s\n", cwd);
    else
        perror("getcwd() error");
    char str[80];
    strcpy(str, cwd);
    strcat(str, "/");
    strcat(str, "MA14");
    strcat(str, ".txt");
    printf("String obtained on concatenation: %s\n", str);
    int permission = get_permission(str);
    printf("permission is: %d\n", permission);
    return 0;
}


int get_permission(char *file_path_name){
    char c;
    size_t nbytes;
    nbytes = sizeof(c);
    int fd = open(file_path_name, O_RDONLY | O_EXCL);
    read(fd, &c, nbytes);
    printf("c = % d\n", c);
    close(fd);
    return c;
}

Current working dir: ~/cmake-build-debug
String obtained on concatenation: ~cmake-build-debug/MA14.txt
c =  48
permission is: 48

Process finished with exit code 0

评论中你有2个选项,我有第三个选项。选项是:

  1. 减去'0​​'得到整数值。
  2. Return c == '1'
  3. 首先将值存储为二进制:

    char c = 0; // Note this is the integer, not '0'
    write(fd, &c, 1);
    

虽然我不建议第三种选择。对于您的用例,通常的做法是将文件保存为文本格式 (ASCII),以便您可以在文本编辑器中阅读它以进行故障排除。所以使用前两个选项中的任何一个。

您提供的代码存在三个错误,因此您得不到想要的结果。

第一个错误出现在函数声明中,因为 return 类型必须是 char。

char get_permission(char *file_path_name);

第二个是在 get_permission 中打印 c 的值,因为 printf 必须打印字符 [%c] 而不是整数 [%d]。

printf("c = %c\n", c);

第三个在 main 函数中,因为你必须知道我们上面所说的来调整类型。

int permission = get_permission(str);

printf("permission is: %c\n", permission);

我重新发布更正后的代码。 我希望你觉得它有用。

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <fcntl.h>
#include <string.h>

char get_permission(char *file_path_name);

int main() {
    char cwd[1024];
    if (getcwd(cwd, sizeof(cwd)) != NULL)
        fprintf(stdout, "Current working dir: %s\n", cwd);
    else
        perror("getcwd() error");
    char str[80];
    strcpy(str, cwd);
    strcat(str, "/");
    strcat(str, "MA14");
    strcat(str, ".txt");
    printf("String obtained on concatenation: %s\n", str);
    int permission = get_permission(str);
    printf("permission is: %c\n", permission);
    return 0;
}

char get_permission(char *file_path_name){
    char c;
    size_t nbytes;
    nbytes = sizeof(c);
    int fd = open(file_path_name, O_RDONLY | O_EXCL);
    read(fd, &c, nbytes);
    printf("c = %c\n", c);
    close(fd);
    return c;
}