البرمجة

قراءة مصفوفة الجراف من ملف نصي في C

To read the adjacency matrix from a text file in C, you can follow these steps:

  1. Open the file in read mode.
  2. Read each line from the file.
  3. Parse the line to extract the integers representing the matrix elements.
  4. Store the integers in the graph array.

Here’s an example implementation:

c
#include #define V 5 // Assuming the size of the matrix is fixed void readGraphFromFile(int graph[V][V], const char* filename) { FILE *file = fopen(filename, "r"); if (file == NULL) { printf("Error opening file!\n"); return; } for (int i = 0; i < V; i++) { for (int j = 0; j < V; j++) { fscanf(file, "%d", &graph[i][j]); } } fclose(file); } int main() { int graph[V][V]; readGraphFromFile(graph, "graph.txt"); // Display the graph (optional) for (int i = 0; i < V; i++) { for (int j = 0; j < V; j++) { printf("%d ", graph[i][j]); } printf("\n"); } return 0; }

Make sure your text file (graph.txt in this case) contains the matrix elements in the same format as shown in your inline input. Each row should be separated by a newline and elements within a row should be separated by spaces.

If you have any specific requirements or questions about this code, feel free to ask!

المزيد من المعلومات

لقراءة مصفوفة الجراف الخاصة بك من ملف نصي في لغة C، يمكنك استخدام دالة مشابهة للمثال السابق ولكن مع بعض التعديلات إذا كان تنسيق الملف النصي يتطلب ذلك. إليك توضيحاً للخطوات:

  1. فتح الملف بوضع القراءة.
  2. قراءة كل سطر من الملف.
  3. تحليل السطر لاستخراج الأعداد الصحيحة التي تمثل عناصر المصفوفة.
  4. تخزين الأعداد في مصفوفة الجراف.

هنا مثال على تنفيذ ذلك:

c
#include #define V 5 // نفترض أن حجم المصفوفة ثابت void readGraphFromFile(int graph[V][V], const char* filename) { FILE *file = fopen(filename, "r"); if (file == NULL) { printf("خطأ في فتح الملف!\n"); return; } for (int i = 0; i < V; i++) { for (int j = 0; j < V; j++) { fscanf(file, "%d", &graph[i][j]); } } fclose(file); } int main() { int graph[V][V]; readGraphFromFile(graph, "graph.txt"); // عرض المصفوفة (اختياري) for (int i = 0; i < V; i++) { for (int j = 0; j < V; j++) { printf("%d ", graph[i][j]); } printf("\n"); } return 0; }

تأكد من أن ملف النص (graph.txt في هذه الحالة) يحتوي على عناصر المصفوفة بنفس التنسيق الذي ذكرته في مثال الإدخال المباشر. يجب أن تكون كل صف مفصول بسطر جديد وأن تكون العناصر داخل كل صف مفصولة بمسافات.

إذا كان لديك أي متطلبات محددة أو استفسارات حول هذا الكود، فلا تتردد في طرحها!

مقالات ذات صلة

زر الذهاب إلى الأعلى

هذا المحتوى محمي من النسخ لمشاركته يرجى استعمال أزرار المشاركة السريعة أو تسخ الرابط !!