作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我最近开始学习 C,但是,我正在编写一小段示例/练习代码,它恰好显示错误。我使用文件描述符,“打开”命令中的一些标志不起作用,即使我似乎包含了正确的头文件。这可能是一个我忽略的简单问题。
问题出现在“S_IRUSR”和“S_IWUSR”似乎未定义的地方。在此之后我没有再编写任何代码,因此我将发布我所拥有的所有代码。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
void usage(char *prog_name, char *filename)
{
printf("Usage: %s <data to add to %s>\n", prog_name, filename);
exit(0);
}
void fatal(char *);
void *ec_malloc(unsigned int);
int main(int argc, char *argv[])
{
int fd; //file descriptor
char *buffer, *datafile;
buffer = (char *) ec_malloc(100);
datafile = (char *)ec_malloc(20);
strcpy(datafile, "/tmp/notes");
if (argc > 2)
usage(argv[0], datafile);
strcpy(buffer, argv[1]);
printf("[DEBUG] buffer\t @ %p: \'%s\'\n", buffer, buffer);
printf("[DEBUG] datafile\t @ %p: \'%s\'\n", datafile, datafile);
strncat(buffer, "\n", 1);
//opening file - this line of code is causing the problem.
fd = open(datafile, O_WRONLY |O_CREAT | O_APPEND, S_IRUSR|S_IWUSR)
}
void fatal(char *message)
{
char error_message[100];
strcpy(error_message, "[!!] Fatal Error ");
strncat(error_message, message, 83);
perror(error_message);
exit(-1);
}
void *ec_malloc(unsigned int size)
{
void *ptr;
ptr = malloc(size);
if (ptr == NULL)
fatal("in ec_malloc() on memory allocation");
return ptr;
}
就像我说的,我不相信其中有任何拼写错误,据我所知,那里有正确的标题,但如果我错了,请纠正我。感谢您的帮助。
最佳答案
您忘记包含 stdio.h,并且 S_IWUSR 上有拼写错误,并且忘记了分号。
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
void usage(char *prog_name, char *filename)
{
printf("Usage: %s <data to add to %s>\n", prog_name, filename);
exit(0);
}
void fatal(char *);
void *ec_malloc(unsigned int);
int main(int argc, char *argv[])
{
int fd; //file descriptor
char *buffer, *datafile;
buffer = (char *) ec_malloc(100);
datafile = (char *)ec_malloc(20);
strcpy(datafile, "/tmp/notes");
if (argc > 2)
usage(argv[0], datafile);
strcpy(buffer, argv[1]);
printf("[DEBUG] buffer\t @ %p: \'%s\'\n", buffer, buffer);
printf("[DEBUG] datafile\t @ %p: \'%s\'\n", datafile, datafile);
strncat(buffer, "\n", 1);
//opening file - this line of code is causing the problem.
fd = open(datafile, O_WRONLY |O_CREAT | O_APPEND, S_IRUSR|S_IWUSR);
}
void fatal(char *message)
{
char error_message[100];
strcpy(error_message, "[!!] Fatal Error ");
strncat(error_message, message, 83);
perror(error_message);
exit(-1);
}
void *ec_malloc(unsigned int size)
{
void *ptr;
ptr = malloc(size);
if (ptr == NULL)
fatal("in ec_malloc() on memory allocation");
return ptr;
}
关于C I/O 程序不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28654342/
我是一名优秀的程序员,十分优秀!