c语言遍历文件里的行数据
时间: 2023-05-22 07:01:57 浏览: 135
可以使用C语言中的文件操作函数来遍历文件里的行数据,具体的实现方法可以参考以下代码:
```c
#include <stdio.h>
int main() {
FILE *fp;
char line[100];
fp = fopen("file.txt", "r");
if (fp == NULL) {
printf("Failed to open file\n");
return 1;
}
while (fgets(line, sizeof(line), fp)) {
printf("%s", line);
}
fclose(fp);
return 0;
}
```
这段代码可以打开名为"file.txt"的文件,并逐行读取文件内容并输出到控制台。
相关问题
linux 用c语言遍历文件系统目录结构
在Linux系统中,可以使用C语言编写代码遍历文件系统目录结构,以下是一个示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
void listdir(char *path) {
DIR *dir;
struct dirent *entry;
if (!(dir = opendir(path))) {
perror("opendir");
exit(EXIT_FAILURE);
}
while ((entry = readdir(dir))) {
char filename[1024];
struct stat st;
snprintf(filename, sizeof(filename), "%s/%s", path, entry->d_name);
if (entry->d_type == DT_DIR) {
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
continue;
printf("dir: %s\n", filename);
listdir(filename);
} else {
printf("file: %s\n", filename);
}
}
closedir(dir);
}
int main(int argc, char **argv) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <directory>\n", argv[0]);
exit(EXIT_FAILURE);
}
listdir(argv[1]);
return 0;
}
```
这个程序使用了 `opendir()` 和 `readdir()` 函数来打开和读取目录。它使用 `struct dirent` 结构体来存储每个目录项的信息。如果目录项是一个目录,则递归调用 `listdir()` 函数来处理该目录。否则,它将打印文件名。
需要注意的是,这个程序只适用于Linux系统,因为它使用了Linux特有的目录项类型。在其他操作系统上,可能需要使用不同的函数和数据结构来遍历目录。
linux 用c语言遍历
遍历什么呢?文件系统目录结构,或者说是链表、数组等数据结构?以下是一些遍历的示例代码:
1. 遍历文件夹中的所有文件和子文件夹
```c
#include <stdio.h>
#include <dirent.h>
void listdir(const char *path) {
struct dirent *entry;
DIR *dir = opendir(path);
if (dir == NULL) {
return;
}
while ((entry = readdir(dir)) != NULL) {
if (entry->d_type == DT_DIR) {
char path2[1024];
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
snprintf(path2, sizeof(path2), "%s/%s", path, entry->d_name);
listdir(path2);
} else {
printf("%s/%s\n", path, entry->d_name);
}
}
closedir(dir);
}
int main() {
listdir("/path/to/folder");
return 0;
}
```
2. 遍历链表
```c
#include <stdio.h>
struct node {
int data;
struct node *next;
};
void traverse_list(struct node *head) {
while (head != NULL) {
printf("%d\n", head->data);
head = head->next;
}
}
int main() {
struct node *head = NULL;
// add nodes to linked list
traverse_list(head);
return 0;
}
```
3. 遍历数组
```c
#include <stdio.h>
void traverse_array(int arr[], int size) {
for (int i = 0; i < size; i++) {
printf("%d\n", arr[i]);
}
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);
traverse_array(arr, size);
return 0;
}
```