2014-01-07 74 views
1
#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)); 
    } 
} 

如何使用write()函數將integer var寫入文件? 這是我的代碼。問題出在func()。如果我使用charsconst int它工作正常。如何使用c中的write()函數將整數變量寫入文件

+4

請閱讀「寫」手冊。 –

+0

「int」或「const int」不應該顯示不同的結果。 – alk

回答

2

第一個,閱讀write()man page。它寫入bytes,而不是element types

所以,你試圖實現,不能直接與write()完成。你需要使用snprintf()intchar字符串,您可以與write()使用轉換。請檢查以下代碼。

1.定義char陣列,print所述的int指針使用snprintf()該數組的值。
2.使用char數組作爲參數write()。它會工作。

NOTE:向系統調用和庫調用添加一些錯誤檢查總是一個最佳實踐。它在失敗的情況下提供了許多有用的信息。

#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); 
     } 
} 
+0

不應該是snprintf(buf,(sizeof * num + 1),「%d」,* num);? snprintf寫入最大尺寸的字符,包括空終止字符。當然buf應該是buf [5] –

相關問題