libhdfs 的C API

1.概述

libhdfs是基于JNI的hdfs的C应用接口。它提供了通过C接口访问HDFS的功能。libhdfs库是Hadoop发行版中一部分,已经编译好了,所在位置一般是${HADOOP_HOME}/lib/native/libhdfs.so 。不同的版本库文件所在位置稍微不同。

2.API

libhdfs中的没有API描述一般在hdfs.h中,该头文件的位置一般在${HADOOP_HOME}/include/hdfs.h,不同的版本头文件所在位置稍微不同。
具体每个接口的功能和C语言中文件操作接口类似。

3.一个简单的程序

// hdfs_test.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "hdfs.h"

int main(int argc, char **argv) 
{
    /*  
     * Connection to hdfs.
     */
    hdfsFS fs = hdfsConnect("default", 0); 
    if(!fs)
    {   
        fprintf(stderr, "Failed to connect to hdfs.\n");
        exit(-1);
    }   

    /*  
     * Create and open a file in hdfs.
     */
    const char* writePath = "/tmp/testfile.txt";
    hdfsFile writeFile = hdfsOpenFile(fs, writePath, O_WRONLY|O_CREAT, 0, 0, 0); 
    if(!writeFile) 
    {   
        fprintf(stderr, "Failed to open %s for writing!\n", writePath);
        exit(-1);
    }   

    /*  
     * Write data to the file.
     */
    char* buffer = "Hello, World!";
    tSize num_written_bytes = hdfsWrite(fs, writeFile, (void*)buffer, strlen(buffer)+1);

    /*  
     * Flush buffer.
     */
    if (hdfsFlush(fs, writeFile)) 
    {   
        fprintf(stderr, "Failed to 'flush' %s\n", writePath);
        exit(-1);
    }

    /*
     * Close the file.
     */
    hdfsCloseFile(fs, writeFile);

    /*
     * Disconnect to hdfs.
     */
    hdfsDisconnect(fs);

    return 0;
}

4.如何连接libhdfs

我们知道:libhdfs.so所在的路径为${HADOOP_HOME}/lib/native,hdfs.h所在的路径为${HADOOP_HOME}/include,那么编译命令为:
gcc hdfs_test.c -I${HADOOP_HOME}/include -L${HADOOP_HOME}/lib/native -lhdfs -o hdfs_test

5.经常出现的问题

最经常出现的应该是CLASSPATH的设定问题,因为如果CLASSPATH设定不正确,会导致上面的程序编译不通过或是执行报错。
CLASSPATH的正确设定是将${HADOOP_HOME}下的*.jar文件都添加到CLASSPATH中。

6.线程安全性

libhdfs是线程安全的。


参考: HDFS C API



你可能感兴趣的:(c,hadoop,api,hdfs)