read csv
This commit is contained in:
		
							
								
								
									
										44
									
								
								content/posts/2023/c/read-csv.md
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										44
									
								
								content/posts/2023/c/read-csv.md
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,44 @@
 | 
			
		||||
---
 | 
			
		||||
title: "♾️ Чтение CSV на Си"
 | 
			
		||||
date: 2023-06-05T22:08:07+03:00
 | 
			
		||||
draft: false
 | 
			
		||||
tags: [c, tips]
 | 
			
		||||
---
 | 
			
		||||
 | 
			
		||||
## Файл CVS
 | 
			
		||||
 | 
			
		||||
```text
 | 
			
		||||
id,text,from
 | 
			
		||||
1,text message,twitter
 | 
			
		||||
2,i live this language,book
 | 
			
		||||
```
 | 
			
		||||
 | 
			
		||||
## Код
 | 
			
		||||
 | 
			
		||||
```c
 | 
			
		||||
#include <stdio.h>
 | 
			
		||||
#include <string.h>
 | 
			
		||||
 | 
			
		||||
int main() {
 | 
			
		||||
    char buffer[80];
 | 
			
		||||
    FILE *stream = fopen("example.csv", "r");
 | 
			
		||||
 | 
			
		||||
    while (fgets(buffer, 80, stream)) {
 | 
			
		||||
        // Символ разделитель
 | 
			
		||||
        char *token = strtok(buffer, ",");
 | 
			
		||||
 | 
			
		||||
        // Если нам нужен только первый столбец каждой строки
 | 
			
		||||
        if (token) {
 | 
			
		||||
            printf("%s\n", token);
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
        // Если нам нужны все значения подряд
 | 
			
		||||
        while (token) {
 | 
			
		||||
            printf("%s\n", token);
 | 
			
		||||
            token = strtok(NULL, ",");
 | 
			
		||||
        }
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    return 0;
 | 
			
		||||
}
 | 
			
		||||
```
 | 
			
		||||
		Reference in New Issue
	
	Block a user