[英]how to write integer var to file using write() function in c
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pthread.h>
void *func(void *ptr);
int file;
int main()
{
pthread_t thread1, thread2;
int iret1, iret2;
int p;
p=1;
file=open("file1.txt", O_CREAT | O_TRUNC | O_RDWR , 0666);
iret1 = pthread_create(&thread1, NULL, func, (void *)&p);
pthread_join(thread1, NULL);
close(file);
exit(0);
}
void *func(void *ptr)
{
int *num;
int i;
num = (int *)ptr;
printf("%d ", *num);
for (i=0; i<10; i++)
{
printf("%d", *num);
write(file, *num, sizeof(*num));
}
}
How to write integer var
to file using write()
function in c? c - 如何使用c中的
write()
函数将integer var
写入文件? This is my code.这是我的代码。 The problem is in the
func()
.问题出在
func()
。 If I use chars
or const int
it's working fine.如果我使用
chars
或const int
它工作正常。
First , read the man page of write()
.首先,阅读
write()
的手册页。 It writes bytes
, not element types
.它写入
bytes
,而不是element types
。
So, what you are trying to achieve, cannot be accomplished directly with write()
.因此,您要实现的目标无法直接使用
write()
。 you need to use snprintf()
to convert the int
to char
string, which you can use with write()
.您需要使用
snprintf()
将int
转换为char
字符串,您可以将其与write()
。 Please check the following code.请检查以下代码。
1. Define a char
array, print
the value of the int
pointer to that array using snprintf()
. 1.定义一个
char
数组,使用snprintf()
print
指向该数组的int
指针的值。
2. Use the char
array as the argument of write()
. 2.使用
char
数组作为write()
的参数。 It'll work.它会工作。
NOTE: It's always a best practice to add some error check to the system calls and library calls.注意:向系统调用和库调用添加一些错误检查始终是最佳实践。 It provides many useful information in the case they fail.
它在失败的情况下提供了许多有用的信息。
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pthread.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
void *func(void *ptr);
int file;
int main()
{
pthread_t thread1, thread2;
int iret1, iret2;
int p;
p=1;
file=open("file1.txt", O_CREAT | O_TRUNC | O_RDWR , 0666);
iret1 = pthread_create(&thread1, NULL, func, (void *)&p);
pthread_join(thread1, NULL);
close(file);
exit(0);
}
void *func(void *ptr)
{
int *num;
int i, ret = -1;
num = (int *)ptr;
char buf[4] = {0}; //to use with write()
printf("%d\n", *num);
for (i=0; i<10; i++)
{
printf("%d", *num);
memset(buf, 0, sizeof (buf));
snprintf(buf, sizeof *num, "%d", *num); //print to buffer
ret = write(file, buf, strlen(buf)); //write the buf to file
if (ret < 0) //check for erroneous condition
printf("ret is %d, errno %d\n", ret, errno);
}
}
write(fd, &var, sizeof(i));写(fd, &var, sizeof(i)); is a short fix for this question.
是这个问题的简短解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.